有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing Java:无法在JFrame中显示图像

我正在学习用JAVA制作gui,并尝试在我的JFrame中添加一个图像,这是我尝试的代码:

    public class MyApp extends JFrame {

    private ImageIcon img;
    private JLabel imglabel;

    public MyApp(){
        setLayout(new FlowLayout());

        img = new ImageIcon(getClass().getResource("img.jpg"));
        //adding the label for the above Icon
        imglabel = new JLabel("this is the image");
        add(imglabel);
    }

    public static void main(String[] args) {
        MyApp app = new MyApp();
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.pack();
        app.setVisible(true);
        app.setTitle("reminder");
    }
}

但我看不到屏幕上显示的任何图像!我哪里出错了

此外,映像和类位于同一目录中:

谢谢你的帮助:)


共 (1) 个答案

  1. # 1 楼答案

    图标从未设置

    imglabel = new JLabel("this is the image");
    

    应该是

    imglabel = new JLabel("this is the image");
    imgLabel.setIcon(img); // or use the 3 arg constructor for JLabel