[英]Image Icon not showing on JButton
我目前正在用 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);
你可以像这样加载你的 ImageIcon:
ImageIcon diceIcon = new ImageIcon(getClass().getResource("/images/DiceIcon.png"));
阅读有关如何使用图标的 Java 教程了解更多信息。
您可能应该使用ImageIcon.getImageLoadStatus()
来确保在尝试在JButton
上呈现图像之前加载的图像没有错误。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.