2013-12-11 168 views
0

我目前正在用java製作遊戲並且有一個JButton,它有一個圖像圖標。唯一的問題是沒有顯示圖像,甚至在調試窗口中也沒有發生錯誤。JButton上沒有顯示圖像圖標

我打包了我的程序(請參閱屏幕截圖 - https://db.tt/N9CwHJdf)。我使用的代碼寫在下面,如果有人能解決這個問題,我會非常感激。謝謝。

//Button Image 
ImageIcon diceIcon = new ImageIcon("Client/images/DiceIcon.png"); 

//Create Button 
JButton rollDice = new JButton("Roll Dice", diceIcon); 
rollDice.setForeground(Color.darkGray); 
rollDice.setFocusPainted(false); 
rollDice.setPreferredSize(new Dimension(284,50)); 
rollDice.setBorder(BorderFactory.createLineBorder(Color.orange)); 
rollDice.setBackground(Color.orange); 
rollDice.setToolTipText("Click to roll dice and continue playing"); 
rollDice.addActionListener(this); 
+0

DiceIcon = new ImageIcon(「Client/images/DiceIcon.png」);嘗試給出完整的圖像路徑 – user2277872

+0

我已經添加了以下行:DiceIcon = new ImageIcon(「src/Client/images/DiceIcon.png」);並仍然不起作用:( –

+0

嘗試從您的項目中的開始文件獲取路徑,並查看是否有效...圖像是棘手的當涉及到路徑 – user2277872

回答

0

您可以加載您的ImageIcon這樣的:

ImageIcon diceIcon = new ImageIcon(getClass().getResource("/images/DiceIcon.png")); 

閱讀Java教程上How to Use Icons更多。

+0

我有同樣的問題 但在我的情況下,它必須看起來像這樣(複製代碼): 'ImageIcon diceIcon = new ImageIcon(getClass()。getResource(「/ images/DiceIcon.png」)); static JButton mybutton = new JButton(「mybutton」 ,diceIcon); 公共靜態無效的主要(字串[] args){ 附加(爲myButton); }' 但後來它強調的getClass(),並顯示錯誤,因爲它是靜態 任何浩的想法。 W解決這個問題? –

+0

@Tom Lenc:試試這個: import javax.swing。*; public class Foo extends JFrame private ImageIcon diceIcon = new ImageIcon(getClass()。getResource(「/ images/DiceIcon.png」)); 私人JButton mybutton =新JButton(「mybutton」,diceIcon); public Foo(){ add(mybutton); pack(); (true);}}}}}}} {} public static void main(String [] args){Foo()} setFisible(true); } } –

+0

不起作用。 我必須在main方法之後的特定部分之後添加該按鈕,這意味着mybutton必須是靜態的,這意味着ImageIcon也必須是靜態的,但後來我會拋出一個錯誤。 這很難解釋..(我不是美國人) –

0

您應該使用ImageIcon.getImageLoadStatus()以確保在嘗試在JButton上渲染圖像之前加載的圖像沒有錯誤。