图像图标未在java中显示

图像图标未在java中显示,java,macos,swing,fullscreen,imageicon,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

此代码应该显示背景图像和播放器。但它只是有一个粉红色的屏幕。我真的不知道问题出在哪里,这是我的代码

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");
        }
    }    
}
非常感谢

  • JFrame
    不是显示
    图像的合适组件(其容器)

  • 对于
    JFrame
    使用
    paint()
    不是显示图像或自定义绘画、图形的正确方法

  • 使用
    JLabel
    setIcon()
    以防
    JFrame
    用作容器,并且
    JFrame
    中没有任何
    JComponent

  • 使用
    JPanel
    (置于
    JFrame.CENTER
    区域)并覆盖
    paintComponent
    (而不是
    paint
    ),以防将
    JPanel
    用作另一
    JComponent
    的容器

  • 更多

  • JFrame
    不是显示
    图像的合适组件(其容器)

  • 对于
    JFrame
    使用
    paint()
    不是显示图像或自定义绘画、图形的正确方法

  • 使用
    JLabel
    setIcon()
    以防
    JFrame
    用作容器,并且
    JFrame
    中没有任何
    JComponent

  • 使用
    JPanel
    (置于
    JFrame.CENTER
    区域)并覆盖
    paintComponent
    (而不是
    paint
    ),以防将
    JPanel
    用作另一
    JComponent
    的容器

  • 更多


  • 使用图像时,您希望通过URL将其加载到
    Class.getResource()
    ,该URL返回一个URL。将字符串传递给
    ImageIcon
    将导致通过文件系统查找图像。虽然这可能在IDE开发期间起作用,但在部署时您会发现它不起作用。最好现在就改变。要使用此方法,请执行以下操作

    ImageIcon icon = new ImageIcon(Images.class.getResource("/Users/georgebastow/Picture/background.jpg"));
    
    但要使其工作,您的文件结构需要如下所示

    ProjectRoot
              src
                 Users
                      georgebastow
                                Picture
                                      background.jpg
    
    public static void main(String[] args) {
        SwingUtiliities.invokeLater(new Runnable(){
            public void run() {
                new Images();
            }
        });
    }
    
    一种更常见的方法是将映像放在src中的reousrces文件夹中

    ProjectRoot
              src
                 resources
                         background.jpg
    
    并使用此路径

    ImageIcon icon = new ImageIcon(Images.class.getResource("/resources/background.jpg"));                     
    
    构建时,IDE将图像传输到类路径


    旁注

    • 不要在顶级容器上绘画,如
      JFrame
      。而是使用
      JPanel
      JComponent
      并重写
      paintComponent
      方法。如果使用
      JPanel
      ,还应在
      paintComponent
      方法中调用
      super.paintComponent
    • 像这样从线程运行Swing应用程序

      ProjectRoot
                src
                   Users
                        georgebastow
                                  Picture
                                        background.jpg
      
      public static void main(String[] args) {
          SwingUtiliities.invokeLater(new Runnable(){
              public void run() {
                  new Images();
              }
          });
      }
      

    • 不要调用
      Thread.sleep()
      。当从EDT运行时(就像您应该做的),您将阻止它。如果您想要的是动画,请使用
      java.swing.Timer
      。即使它不是动画,也要使用它!有关
      定时器
      程序,请参阅

    • 正如@mKorbel所提到的,您从未向框架添加任何内容

    更新

    运行此示例。我还忘了提到,当您在
    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();
                }
            });
        }
    }
    

    使用图像时,您希望通过URL将其加载到
    Class.getResource()
    ,该URL返回一个URL。将字符串传递给
    ImageIcon
    将导致通过文件系统查找图像。虽然这可能在IDE开发期间起作用,但在部署时您会发现它不起作用。最好现在就改变。要使用此方法,请执行以下操作

    ImageIcon icon = new ImageIcon(Images.class.getResource("/Users/georgebastow/Picture/background.jpg"));
    
    但要使其工作,您的文件结构需要如下所示

    ProjectRoot
              src
                 Users
                      georgebastow
                                Picture
                                      background.jpg
    
    public static void main(String[] args) {
        SwingUtiliities.invokeLater(new Runnable(){
            public void run() {
                new Images();
            }
        });
    }
    
    一种更常见的方法是将映像放在src中的reousrces文件夹中

    ProjectRoot
              src
                 resources
                         background.jpg
    
    并使用此路径

    ImageIcon icon = new ImageIcon(Images.class.getResource("/resources/background.jpg"));                     
    
    构建时,IDE将图像传输到类路径


    旁注

    • 不要在顶级容器上绘画,如
      JFrame
      。而是使用
      JPanel
      JComponent
      并重写
      paintComponent
      方法。如果使用
      JPanel
      ,还应在
      paintComponent
      方法中调用
      super.paintComponent
    • 像这样从线程运行Swing应用程序

      ProjectRoot
                src
                   Users
                        georgebastow
                                  Picture
                                        background.jpg
      
      public static void main(String[] args) {
          SwingUtiliities.invokeLater(new Runnable(){
              public void run() {
                  new Images();
              }
          });
      }
      

    • 不要调用
      Thread.sleep()
      。当从EDT运行时(就像您应该做的),您将阻止它。如果您想要的是动画,请使用
      java.swing.Timer
      。即使它不是动画,也要使用它!有关
      定时器
      程序,请参阅

    • 正如@mKorbel所提到的,您从未向框架添加任何内容

    更新

    运行此示例。我还忘了提到,当您在
    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();
                }
            });
        }
    }
    

    您好,我将background.jpg放在res文件夹中,但它要求我将bg更改为ImageIcon,而不是图像。这意味着我不能做g.drawImage(bg,0,0,null);。我尝试将其更改为drawLine,但也没有帮助。您需要像以前在
    ImageIcon
    实例化结束时那样使用.getImage()。确保将
    bg
    保留为
    图像
    您不能绘制和
    ImageIcon
    我已经这样做了,当我运行程序时,它不会显示图像。为什么会发生这种情况。它在整个屏幕上显示为粉红色。我正在使用mac OS X,屏幕将变为全屏,因此dock将在第一秒钟显示。请使用
    bg=ImageIO.read(Images.class.getResource(“/res/background.jpg”);
    并尝试将其包装起来