图像图标没有显示在JButton上

时间:2013-12-11 20:36:40

标签: java user-interface jbutton packaging imageicon

我目前正在使用java制作游戏并拥有一个带有图像图标的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);

3 个答案:

答案 0 :(得分:1)

您可以像这样加载ImageIcon:

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

阅读How to Use Icons上的Java教程了解更多信息。

答案 1 :(得分:0)

在尝试在ImageIcon.getImageLoadStatus()上呈现图片之前,您应该使用JButton来确保加载的图片没有错误。

答案 2 :(得分:0)

javas.swing.Action是Java GUI API中的丑小鸭类:尽管提出了一些有趣的建议,但使用很少,正确使用的示例也很少。

在按钮中使用 Action 时,您可以定义几个通常必须直接向按钮实例中逐个添加的属性,例如图标,工具提示,字幕等。

一个烦人的问题是,Action会用警告覆盖您的按钮设置! 因此,如果您使用Action,请避免设置额外的属性。

您可以定义自己的Action工厂类或扩展AbstractAction并使用putValue(String key, Object value)来设置按钮属性,如下面的代码片段所示。

请确保在通过putValues()设置自己的值时使用Action类中定义的键。

**
* Facility class for AbstractAction
* Remember that Action also extends ActionListener interface
*
*/
class MyAction extends AbstractAction {     
/**
 * Ctor.
 * @param name - The Action.NAME or the button caption
 * @param actionCMD - the Action.ACTION_COMMAND_KEY value
 * @param shortDescription - the tool tip, Action.SHORT_DESCRIPTION
 * @param icon - the default icon, or  Action.SMALL_ICON paramenter.
 */
public MyAction(String name, String actionCMD, String shortDescription, Icon icon) {                   
     putValue(Action.NAME, name);  
     putValue(Action.SHORT_DESCRIPTION, shortDescription);  
     putValue(Action.ACTION_COMMAND_KEY, actionCMD);  
     if(icon != null)
         putValue(Action.SMALL_ICON, icon);
 }  

 /**
  * The action to be performed
  */
 public void actionPerformed(ActionEvent e) {  
    // put your action code here
 }  
} // end class
 
相关问题