Search code examples
javaswingjbuttonimageicon

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?


Solution

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