2012-10-02 191 views
4

我正在編寫一個程序,要求我有一個帶有超過它的圖像的按鈕,但到目前爲止,我還沒有能夠得到它的工作。我檢查了這個網站上的其他幾個帖子,包括How do I add an image to a JButton
我的代碼:如何把圖像放在JButton上?

public class Tester extends JFrame 
{ 
    public Tester() 
    { 
     JPanel panel = new JPanel(); 
     getContentPane().add(panel); 
     panel.setLayout(null); 

     setTitle("Image Test"); 
     setSize(300,300); 
     setLocationRelativeTo(null); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 

     JButton button = new JButton(); 
     try 
     { 
      Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif")); 
      button.setIcon(new ImageIcon(img)); 
     } 
     catch (IOException ex) {} 

     button.setBounds(100,100,100,100); 
     panel.add(button); 
    } 

    public static void main(String[] args) 
    { 
     Tester test = new Tester(); 
     test.setVisible(true); 
    } 
} 

運行此代碼時,將導致錯誤:異常在線程 「主」 java.lang.IllegalArgumentException異常:輸入== NULL!在該行出現此錯誤:

Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif")); 

我不認爲這個錯誤是由於不被Java代碼中找到的文件,我的圖片文件夾是src文件夾中(我使用Eclipse)作爲通過上面的鏈接推薦。
有沒有人有什麼想法可能是什麼問題?
謝謝。

+0

請提供您的項目層次結構中的圖像路徑 – CAMOBAP

+1

您是否真的檢查過'getResource()'的返回值? – vstm

+0

這是圖像路徑:C:\ Documents and Settings \ student \ My Documents \ Dropbox \ ADVCS_Workspace \ Chess_Program \ src \ Images –

回答

9

雖然使用Eclipse,不要將您的圖像保存爲src文件夾,而不是你爲此創建一個Source Folder。請參考關於如何add images to resource folder in Eclipse的鏈接。

+1

+1不錯的鏈接:)燁我認爲這可能是他沒有前鋒斜線 –

+0

更令我關注的是,沒有使用Source FOlder作爲上述說法,因爲OP說圖像在src文件夾中,我懷疑是正確的方式恕我直言 –

+1

資源文件夾僅僅是約定。您不必使用特殊的「資源文件夾」來讀取圖像。你的道路必須是正確的。 – davidXYZ

2

使用此按鈕來創建按鈕。

JButton button = new JButton(new ImageIcon(getClass().getClassLoader() 
              .getResource("Images/BBishopB.gif"))); 

而你正在做的是將Image設置爲圖標。這不起作用,因爲setIcon()方法需要實現接口Icon的對象。希望這可以幫助。

+0

如果無法找到圖像,這不會解決他的問題。而你的答案的第二部分是不正確的,因爲他正在將圖像讀入圖像,然後將該圖像包裹在ImageIcon中。所以這部分代碼是正確的。 –

+0

@GuillaumePolet這部分直接從URL創建ImageIcon,而不涉及'ImageIO'等不必要的部分。 –

+0

你說過了,我引用:_This不起作用,因爲setIcon()方法需要實現Icon interface_的對象。那聲明是不正確的。 –

2

嘗試把一個斜線盼着包名前getResource()像這樣:

Image img = ImageIO.read(getClass().getResource("/Images/BBishopB.gif")); 
1

你可以只找到直接的圖像:

JButton jb = new JButton(new ImageIcon("pic.png")); //pic is in project root folder 
//Tip: After placing the image in project folder, refresh the project in Eclipse. 

,或者圖像將是一個JAR,我通常會創建一個函數來完成的檢索針對我,讓我可以重新使用它。

public static ImageIcon retrieveIcon(String path){ 
    java.net.URL imgUrl = 'classpackage'.'classname'.class.getResource(path); 
    ImageIcon icon = new ImageIcon(imgUrl); 
    return icon; 
} 

然後我會做,

JButton jb = new JButton(retrieveIcon("/pic.png")); 
1
Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif")); 

此行試圖在同一時間,這使得當你得到一個難以追蹤到錯誤的事太多了所有。我建議拆分它:

URL imgURL = getClass().getResource("Images\\BBishopB.gif"); 
Image img = ImageIO.read(imgURL); 

現在你可以使用Eclipse調試器來檢查imgURL的返回值,這對於NPE最有可能的人選。儘管這並不能告訴你爲什麼你會收到錯誤信息,但它會顯着縮小問題範圍。