2013-02-18 21 views
1

編輯:這是一個Netbeans項目。 所以我創建了一個名爲Card的JButton的子類。我正在嘗試在創建時將按鈕設置爲按鈕。定製JButton子類setIcon方法不起作用

package matchinggame; 

public class Card extends JButton { 

    final static ImageIcon defaultIcon = new ImageIcon("cardback.jpg"); 

    ... 

    public Card(int secretIconIndex) { 
     //Set the button's icon to the default icon 
     setIcon(defaultIcon); 
     ... 
    } 

    ... 

} 

如果你想知道,在「cardback.jpg」圖像的位置爲:

C:\Users\Jesse\SkyDrive\Documents\RCS\Grade 12\ICS4U\M9\MatchingGame\src\matchinggame\cardback.jpg 

它是在同一文件夾/包,因爲所有的類,所以我相信我可以離開這樣的相對文件路徑。當我運行程序時,所有的按鈕都只是空白的(沒有文字或圖標)。這是一個構造函數問題還是文件路徑問題?

+2

您是否嘗試過使用絕對路徑? – 2013-02-18 23:47:32

+0

是的,錯誤的路徑是我看的地方。您是否使用過調試器或println語句或記錄器來檢查此時的程序狀態,以查看該圖標是否爲空? – 2013-02-18 23:50:51

+0

以前從未使用絕對路徑,但我只是嘗試了絕對路徑,現在圖像顯示出來!但是現在,這不適用於其他人的計算機......有沒有解決方法? – jessechk 2013-02-18 23:51:37

回答

1

我的問題在問題意見中回答。 brano88和氣墊船充分說鰻魚使用資源,而不是文件路徑。以下解決了我的問題:

final ImageIcon defaultIcon = new ImageIcon(getClass().getResource("/resources/cardback.jpg")); 

我把這個放在我的Card類中。

注意:我將圖像移動到Eclipse中「src」文件夾或Netbeans中「Source Packages」文件夾內的新資源包。

0

如果使用「eclipse」,圖像必須位於文件夾「src」中以使用絕對路徑。 用途:
new File("cardback.jpg").exists() // to see if the file is in the right place

4

如果這是一個Eclipse項目存儲在src/文件夾中的文件夾resources/形象。

setButtonIcon("cardback.jpg"); 

public void setButtonIcon(String filename) { 
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
    InputStream input = classLoader.getResourceAsStream("/"+filename); 
    ImageIcon icon = new ImageIcon(ImageIO.read(input)); 
    super.setIcon(icon); 
} 
+2

我喜歡使用ImageIO'的'但是你可以簡單的使用'ImageIO.read(的getClass()的getResource( 「/ matchinggame/cardback.jpg」);',並得到相同的結果;) – MadProgrammer 2013-02-18 23:57:35