Search code examples
javaswingnetbeansjlabelimageicon

Change jLabel icon


It seems like i'm not the only one with that question but I can't find an answer that solves the problem.

I created a Label and assign an Icon to it using WYSIWYG interface designer.
Now I want to change the icon dynamically during runtime.

The logic way would be like this (my first attempt) :

ImageIcon newIcon = new ImageIcon("SomePath");
jLabel1.setIcon(newIcon); 

When I do this the Icon simply disapears from the interface so I googled it and someone said to "flush" the icon whatever this means I tried it :

ImageIcon newIcon = new ImageIcon("SomePath");
newIcon.getImage().flush();
jLabel1.setIcon(newIcon);

Still having the same problem.. The icon disapears.

What am I doing wrong ?


Update (Full Method) :

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
attempted = myEngine.Attempt('q', word);
if(attempted)
  {
      this.jTextArea1.setText(myEngine.ChangeEncrypt('q', word, this.jTextArea1.getText()));    
  }
  else
  {
      JOptionPane.showMessageDialog(null,"The Letter Q is not in the word", "Error",JOptionPane.WARNING_MESSAGE);
      jButton1.setEnabled(false);
      life ++;
      ImageIcon newIcon = myEngine.UpdatePicture(life);
      newIcon.getImage().flush();
      jLabel1.setIcon(newIcon);
  }

This is the UpdatePicture Method :

public ImageIcon UpdatePicture(int life)
{
  ImageIcon emptyIcon = new ImageIcon();
  if (life == 0)
  {
       ImageIcon iconZero = new ImageIcon("/hang0.gif");
       return iconZero;
  }
  if (life == 1)
  {
      ImageIcon iconOne = new ImageIcon("/hang1.gif");
      return iconOne;
  }
  if (life == 2)
  {
      ImageIcon iconTwo = new ImageIcon("/hang2.gif");
      return iconTwo;
  }
  if (life == 3)
  {
      ImageIcon iconThree = new ImageIcon("/hang3.gif");
      return iconThree;
  }
  if (life == 4)
  {
      ImageIcon iconFour = new ImageIcon("/hang4.gif");
      return iconFour;
  }
  if (life == 5)
  {
      ImageIcon iconFive = new ImageIcon("/hang5.gif");
      return iconFive;
  }
  if (life == 6)
  {
      ImageIcon iconSix = new ImageIcon("/hang6.gif");
      return iconSix;
  }

  return emptyIcon;

}

Not sure the whole code was necessary but still it might help.

The life variable starts at 0.
I checked and in the UpdatePicture it hits the "/hang1.gif"; and returns it.


Solution

  • If the file is in your src folder then :

    ImageIcon ii = new ImageIcon(getClass().getResource("/myFile.gif"));