Reputation: 71
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?
Upvotes: 1
Views: 641
Reputation: 1760
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
Upvotes: 2
Reputation: 1394
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*/
}
Upvotes: 1