我正在学习在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");
}
}
但我看不到屏幕上正在显示任何图像!我哪里做错了?
图像和类也位于同一目录中:
谢谢您的帮助 :)
最佳答案
该图标从未设置!
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