我正在学习在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");
}
}
但是我看不到屏幕上显示的任何图像!我哪里出错了?
图像和类也在同一目录中:
感谢您的帮助:)
答案 0 :(得分:2)
永远不会设置图标!
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