Search code examples
javaiconsjlabel

Checking whether JLabel's Icon is a particular Icon or not


I have this code:

if(seatE1.getIcon() == particular icon)
{
    // do something
}

I don't know what to write in particular icon. Should I write the path of the icon I want or what? If there is a better way to do it please let me know.


Solution

  • What you could do is when you instantiate an imageIcon, put the filename as the description and then do toString(), which returns the description. Here's an example:

    private final String IMAGEPATH = "image.png";
    JLabel label = new JLabel(new ImageIcon(IMAGEPATH, IMAGEPATH));
    
    if(label.getIcon().toString() == "image.png")
    {
      //do something
    }
    

    That's one basic way of doing it, or you could make a class that extends ImageIcon and in the constructor assign the file path to a variable and make a method like getPath() which returns that variable.

    (I haven't tested that code exactly, but I've used essentially the same thing in one of my programs before and it worked)