ImageIcon不在java中显示

Pil*_*kin 1 java macos swing fullscreen imageicon

该代码应该显示背景图像和播放器.但它只是一个粉红色的屏幕.我无法确定问题的来源,这是我的代码.

package main;

import java.awt.*;
import javax.swing.ImageIcon;    
import javax.swing.JFrame;

public class Images extends JFrame {

    public static void main(String Args[]) {

        DisplayMode dm = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN); // This is going to take 4 parameter, first 2 is x and y for resolotion. Bit depth, the number of bits in a cloour
                                                                                            // 16 is your bit depth. the last one is the monitor refresh, it means it will refres how much it wants
        Images i = new Images(); // making an object for this class
        i.run(dm); // making a run method and is taking the dm as a parameter, in this method we are putting stuff on the screen.
    }

    private Screen s; // Creating the Screen, from the Screen.java
    private Image bg; // Background
    private Image pic; // Face icon
    private boolean loaded; // Making the loaded

    //Run method
    private void run(DisplayMode dm) { // this is where we do things for the screen
        setBackground(Color.PINK); // Setting the Background
        setForeground(Color.WHITE); // Setting the ForeGround
        setFont(new Font("Arial", Font.PLAIN, 24)); // setting the font

        s = new Screen(); // now we can call ALL methods from the Screen object
        try {
            s.setFullScreen(dm, this); // This is setting the full screen, it takes in 2 parameters, dm is the display mode, so its setting the display settings, the next part is the this, what is just s, the screen object.
            loadpics(); // calling the loadpics method
            try { // so if that try block works, then it will put it to sleep for 5 seconds
                Thread.sleep(5000); // its doing this because, at the bottom (s.restorescreen) this makes it into a window again. so it needs to show it for 5 seconds.
            } catch (Exception ex) {
            }
        } finally {
            s.restoreScreen();
        }
    }

    // Loads Pictures
    private void loadpics() {
        System.out.println("Loadpics == true");
        bg = new ImageIcon("Users/georgebastow/Picture/background.jpg").getImage(); // Gets the background
        pic = new ImageIcon("Users/georgebastow/Picture/Player.png").getImage(); // Gets the Player
        System.out.println("Loaded == true in da future!");
        loaded = true; // If the pics are loaded then...    
    }

    public void paint(Graphics g) {
        if (g instanceof Graphics2D) { // This has to happen, its saying if g is in the class Graphics2D, so if we have the latest version of java, then this will run 
            Graphics2D g2 = (Graphics2D) g; // Were making the Text smooth but we can only do it on a graphcis2D object.
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // we are making the text aniti alias and turning it on!(it means making the text smooths! :) )
        }
        if(loaded == true){
            System.out.println("Loaded == true3");
            g.drawImage(bg,0,0,null);
            g.drawImage(pic, 170, 180, null);
            System.out.println("Loaded == true4");
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)

提前谢谢了

Pau*_*tha 6

使用图像时,您希望通过URL加载它们Class.getResource(),返回URL.传递一个字符串ImageIcon将导致通过文件系统查找图像.虽然这可能在IDE的开发过程中起作用,但您会发现它在部署时不起作用.现在更好地进行更改.要使用此方法,您需要执行此操作

ImageIcon icon = new ImageIcon(Images.class.getResource("/Users/georgebastow/Picture/background.jpg"));
Run Code Online (Sandbox Code Playgroud)

为了使其工作,您的文件结构需要看起来像这样

ProjectRoot
          src
             Users
                  georgebastow
                            Picture
                                  background.jpg
Run Code Online (Sandbox Code Playgroud)

更常见的方法是将图像放在src中的reousrces文件夹中

ProjectRoot
          src
             resources
                     background.jpg
Run Code Online (Sandbox Code Playgroud)

并使用此路径

ImageIcon icon = new ImageIcon(Images.class.getResource("/resources/background.jpg"));                     
Run Code Online (Sandbox Code Playgroud)

构建时,IDE会将图像传输到类路径.


边注

  • 不要在顶级容器上涂漆JFrame.而是使用JPanel或JComponent覆盖该paintComponent方法.如果使用JPanel,你也应该调用super.paintComponent的paintComponent方法.
  • 像这样从Event Dispatch Thread 运行Swing应用程序

    public static void main(String[] args) {
        SwingUtiliities.invokeLater(new Runnable(){
            public void run() {
                new Images();
            }
        });
    }
    
    Run Code Online (Sandbox Code Playgroud)

    见初始线程

  • 不要打电话Thread.sleep().当从EDT运行时(就像你应该的那样),你将阻止它.而是使用java.swing.Timer你正在寻找的if动画.即使它不是动画,仍然使用它!见这个例子的Timer程序.

  • 同样正如@mKorbel所提到的,你永远不会在框架中添加任何内容.

UPDATE

运行此示例.我也忘了提,当你画上JPanel你的时候也想要覆盖getPreferredSize().这将为您的面板提供一个尺寸.

src/resources/stackoverflow5.png

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestImage {

    public TestImage() {
        JFrame frame = new JFrame("Test Image");
        frame.add(new NewImagePanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public class NewImagePanel extends JPanel {

        private BufferedImage img;

        public NewImagePanel() {
            try {
                img = ImageIO.read(TestImage.class.getResource("/resources/stackoverflow5.png"));
            } catch (IOException ex) {
                System.out.println("Could not load image");
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(600, 600);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestImage();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)