2016-05-23 52 views
2

我学习,使图形用户界面在Java中,我试图在我的JFrame中添加图像无法显示图像,这是我试过的代码:的Java:在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

是在同一目录类的形象呢?如果它是一个罐子,罐子里是否包含图像? – MadProgrammer

+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 
+0

它应该是“imglabel”我猜,并且抱歉,但它不适合队友! –

+0

确定..而不是使用图像图标加载图像,使用'ImageIO.read(URL)' - 它将提供有用的信息,如果它无法找到或加载图像。 –

+0

已更改:'imglabel.new JLabel(“这是img”)'到'imglabel = new JLabel(img)'并且它工作正常!感谢您的帮助 –