0

i have created a form application with an image that is displayed using the icon property in the label

jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/replacment.jpg"))); // NOI18N
        getContentPane().add(jLabel2);
        jLabel2.setBounds(640, 220, 68, 30);

the main idea is when the user presses a certain button , the image would disappear like this

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("")));
    }     

And it works successfully , I tried to use the getIcon function to alter the code of the program depending on the image displayed in the label , for example

if(jLabel2.getIcon()==""){
  do something 
}   

but i get an error saying : incomparable types Java.swing.icon and Java.lang.string.

so is there a way to do an if statement depending on the icon displayed by the Label?

Mike K.
  • 3,751
  • 28
  • 41

1 Answers1

3

When you want to remove the icon use setIcon(null) then in your if statement check if the Icon is null:

if (jLabel2.getIcon() == null)

Comparing String to Icon is wrong, as the error says you just can't do that.

Mike K.
  • 3,751
  • 28
  • 41
  • thanks , that does work . but is there a method to do a statement depending on 2 separate icons . we have A.jpg and B.jpg i mean what if the icon isn't null but indeed just another image what method can i use to achieve the same goal – Amro Raed El Maadawi Feb 26 '12 at 22:21
  • ImageIcon's toString implementation returns description if its set you could set description with the filename and compare them or extend Imageicon and override toString so you could compare them. – Mike K. Feb 26 '12 at 23:24
  • Another option is to use a `JToggleButton` as shown [here](http://stackoverflow.com/a/6743726/418556). – Andrew Thompson Feb 27 '12 at 03:02