简体   繁体   中英

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

Here's the problem. Button is just a simple JButton without content, and with conditions I'm adding different content into Button. Though when I created the move method, which will switch the two images of two buttons, I failed to attempt to get the ImageIcon of the JButton . It reports this error in the first method:

Icon cannot be converted to ImageIcon

How can I solve that?

Icon is an interface which is implemented by the class ImageIcon so inherently every ImageIcon is an Icon so you can cast the Icon to imageIcon as follows

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*/
}

You can add it through the constructor:

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

The better way is to create an action and create the button from the action. Then you can update the icon of the action and it will be udpated everywhere that action is used: the button, menu bars, popup menus, etc.

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

Then when you need to update the icon it would just be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM