图像不会出现在 JFrame 上

Image won't appear on JFrame

这是我的代码:

    import java.awt.BorderLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;

    public class SenzuView extends JFrame {
      JLabel label;
      public SenzuView(){
        ImageIcon image = new ImageIcon("C:\senzu.jpg");
        label = new JLabel("", image, JLabel.CENTER);
        this.add(label);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setVisible(true);
    }
    public static void main(String[] args) {
        new SenzuView();
    }
}    

问题是框架打开但它是空的并且图像从未出现 提前致谢

我建议您在项目目录中创建一个名为 images 的文件夹。然后给出路径:

ImageIcon image = new ImageIcon("images/senzu.jpg");

这会起作用。

如果您需要绝对路径,请使用

C:/Program Files/workspace/Senzu/images/senzu.jpg

希望它解决了您的问题。

我建议您使用 getClass.getResource,因为如果您稍后想将项目编译成 .jar 文件,图像将随项目一起提供,否则如果您采用解决方案,它们将不会出现您最初开始的路径。

  • 在你的包中创建一个文件夹,你的主要 class 所在的位置。最好叫 'res'
  • 将您的图像移至该包。
  • 像这样初始化图像图标:

    ImageIcon image = new ImageIcon(getClass().getResource("res/senzu.jpg"))
    
  • 以下是我建议您应该如何对 SenzuView 进行编码的示例:

    public SenzuView(){
        setLayout(new BorderLayout());
        ImageIcon image = new ImageIcon(getClass().getResource("res/senzu.jpg"));
        label = new JLabel(image);
        this.add(label, BorderLayout.CENTER);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        setVisible(true)
    }
    

我希望这能解决问题并给你一些其他有用的提示。