2016-07-06 112 views
0

所以我是Java新手,从YouTube上的视频中学习一些基础知识,我正在学习制作GUI /窗口,此刻我正在尝试显示iamges,但我是不知道代码是错误的/旧的或图像不在正确的位置/位置。这是我迄今写的。帮助将不胜感激。谢谢,麻烦您了。GUI图像显示错误

import java.awt.*; 
import javax.swing.*; 

public class FirstGUI extends JFrame { 

    private static Object out; 
    private JLabel label; 
    private JButton button; 
    private JTextField textfield; 

    private ImageIcon image1; 
    private JLabel label1; 

    private ImageIcon image2; 
    private JLabel label2; 


    public FirstGUI() { 

     setLayout (new FlowLayout()); 

     label = new JLabel("Hi, I'm a label!"); 
     add(label); 

     textfield = new JTextField(15); 
     add(textfield); 

     button = new JButton("Click me!"); 
     add(button); 

     button = new JButton("No, CLICK ME!!"); 
     add(button); 

     label = new JLabel("This is the end of the program?"); 
     add(label); 



     image1 = new ImageIcon(getClass().getResource("Apiary.png")); 
     label1 = new JLabel(image1); 

     image2 = new ImageIcon(getClass().getResource("bee.png")); 
     label2 = new JLabel(image2); 
    } 



    public static void main(String[] args) { 

     FirstGUI gui = new FirstGUI(); 
     gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
//*  gui.setSize(400, 400); 
     gui.setVisible(true); 
     gui.setTitle("Hello World"); 
     gui.pack(); 



    } 

} 

我的错误得到什么:

异常线程 “main” 显示java.lang.NullPointerException

在javax.swing.ImageIcon中(来源不明)

在FirstGUI。(FirstGUI.java:39)

在FirstGUI.main(FirstGUI.java:50)

+0

注意:这在图像显示代码被添加之前工作。 – MattRivas

回答

0

第一个您不会将标签添加到框架,所以即使执行它也不会显示图像图标。所以,不要忘记将标签添加到框架:

add(label1); 
add(label2); 

我想你的代码,并为我工作得很好,它只是打印你所提到的错误,当我没有导入图像图标在包我在快乐工作 为此,您需要做的:

右键点击你的src套餐 - >导入 - >常规 - >文件系统然后单击next并选择包含的目录。图像,单击确定,然后添加您在代码中指定的图像。

+0

我试图做你说的我发现如何指向图像并像你说的那样导入它们,然后我试着按照你所说的添加标签,这是我添加它的代码中的一部分。 http://pastebin.com/ynfqiE5F 但运行后,我得到这个错误。 线程“main”中的异常java.lang.NullPointerException \t at javax.swing.ImageIcon。 (未知来源) \t在FirstGUI。 (FirstGUI.java:39) \t at FirstGUI.main(FirstGUI.java:52) 对不起,如果评论晚了,我必须在不同的时区。 – MattRivas

+0

pastebin.com/ynfqiE5F中的代码是不同的,因为它指定了完整的URL('image1 = new ImageIcon(getClass()。getResource(“/ FirstGUI/src/assets/images/Apiary.png”));)',只需使用你刚才提到的代码和图像的名称,在将图像Apiary.png和bee.png导入到包含类的包之后,就不需要指定完整的URL。 –

+0

http://pastebin.com/5Nw7VfA5即使这样我也遇到了同样的问题。 – MattRivas