Question

I have a jlabel that has already an icon, and i want to change the icon when i exit the mouse from the label, i tried this code, it shows no syntax error

private void LabelMouseExited(java.awt.event.MouseEvent evt) {                                   

if(Label.getIcon().toString().equals("cyberjayacinema/images/Blue%20E1"))
    {
        Label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cyberjayacinema/images/red E1.PNG")));
    }

else
    {
            Label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cyberjayacinema/images/white E1.PNG")));
    }

but only the else case works, although the imageicon is set to the if case, so i guess the error is with retrieving the path of the icon, i assume the way i wrote my getImageIcon was wrong, I wish someone can help me with this. thank you

Was it helpful?

Solution

If you just put a System.out.println(label.getIcon().toString()), you will get something like, this

file:/C:/NetBeansProjects/StackOverflow/build/classes/resources/stackoverflow5.png

As you can see, that will not match your case.

You may want to do something like this, to get just the file name

String iconfilename = label.getIcon().toString();
String fileName = iconfilename.substring(iconfilename.lastIndexOf("/"  ) + 1);
System.out.println(fileName);

// output
stackoverflow5.png

Then just check against the file name.

if ("stackoverflow5.png".equals(fileName)) {
    do something
}

OTHER TIPS

This may help you if you are trying to access image from your project folder

 Lable test;
java.net.URL url = ClassLoader.getSystemResource("res/image.png");
test.setIconImage(Toolkit.getDefaultToolkit().getImage(url));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top