2016-07-06 71 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