2013-12-11 173 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上渲染图像之前加载的图像没有错误。