如何让 ImageIcon 显示在 JButton 中?

How can I get the ImageIcon displayed in a 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 中。尽管当我创建将切换两个按钮的两个图像的 move 方法时,我未能尝试获取 JButtonImageIcon。它在第一种方法中报告此错误:

Icon cannot be converted to ImageIcon

我该如何解决?

Icon 是一个由 class ImageIcon 实现的接口,因此本质上每个 ImageIcon 都是一个 Icon,因此您可以按如下方式将 Icon 转换为 imageIcon

public ImageIcon getIcon(){
  return (ImageIcon)button.getIcon(); 
 /*getIcon() returns Icon and  ImageIcon is child 
 of Icon so you can cast as you cast parent class reference to child class in this 
 case it is interface acting as parent*/
}

可以通过构造函数添加:

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