首页 > 解决方案 > 如何让 ImageIcon 显示在 JButton 中?

问题描述

public ImageIcon getIcon(){
   return button.getIcon();
}

public void moveTo(Square j){
   JButton current = new JButton();
   current = button;
   button.setIcon(j.getIcon());
   button.setIcon(current.getIcon());
}

这就是问题所在。Button 只是一个JButton没有内容的简单,并且有条件我正在向 Button 添加不同的内容。虽然当我创建移动方法时,它将切换两个按钮的两个图像,但我未能尝试获取ImageIcon. JButton它在第一种方法中报告此错误:

Icon cannot be converted to ImageIcon

我该如何解决?

标签: javaswingjbuttonimageicon

解决方案


您可以通过构造函数添加它:

JButton button = new JButton("text", icon);

更好的方法是创建一个动作并从该动作创建按钮。然后你可以更新动作的图标,它会在任何使用动作的地方更新:按钮、菜单栏、弹出菜单等。

Action action = new AbstractAction("text", icon) {
    public void actionPerformed(ActionEvent e) {
    }
}
//place the action in an ActionMap 
Jbutton button = new JButton(action);

然后,当您需要更新图标时,它就是

getActionMap().get(key).putValue(Action.LARGE_ICON_KEY, icon); //for buttons
getActionMap().get(key).putValue(Action.SMALL_ICON_KEY, icon); //for menus

推荐阅读