Java 如何在JButton中显示图像图标?

Java 如何在JButton中显示图像图标?,java,swing,jbutton,imageicon,Java,Swing,Jbutton,Imageicon,问题出在这里。按钮只是一个简单的JButton,没有内容,根据条件,我将向按钮添加不同的内容。虽然当我创建move方法时,它将切换两个按钮的两个图像,但我未能尝试获取JButton的ImageIcon。它在第一种方法中报告此错误: public ImageIcon getIcon(){ return button.getIcon(); } public void moveTo(Square j){ JButton current = new JButton(); curren

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

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());
}

如何解决这个问题?

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

Icon cannot be converted to ImageIcon

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

Icon cannot be converted to 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);

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

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);
请参阅,在本例中,代码可能包含对描述GUI状态的模型的引用,以及对要在各种条件下显示的
图像
实例的引用,以及使用模型指示的图像刷新GUI的方法。在本例中,代码可能包含对描述GUI状态的模型的引用、对在各种条件下显示的
图像
实例的引用,以及使用模型指示的图像刷新GUI的方法。