How to reset JLabel

11,309

Solution 1

this is one of possible ways

int n = panel.getComponentCount();
if (n > 0) {
    Component[] components = panel.getComponents();
    for (int i = 0; i < components.length; i++) {
         if (components[i] instanceof JLabel) {
             JLabel label = (JLabel) components[i];
             label.setText("");
         } 
    }
}

Solution 2

No need to re-add them to the panel. It should be enough to simply set the text to an empty string.

If this is not happening, make sure you are doing it on the event dispatch thread, as so:

SwingUtilities.invokeLater(new Runnable() {
   public void run() {
      desks[i].setText("");
   }
});

Solution 3

You don't have to add the labels to your content pane again to reset their text. Just do the following to clear up the label text:

 for(int i=0; i<desks.length; i++)
 {
    desks[i].setText("");
 }
Share:
11,309
Kiril
Author by

Kiril

I am currently doing BSc Computer Science. I am at the first year. I am trying to develop some real programming skills using Java and I do not have much experience with programming.

Updated on June 04, 2022

Comments

  • Kiril
    Kiril almost 2 years

    I am trying to reset an array of JLabels. There are images on the top of the labels so when i press a button the labels are supposed to be reset. I tried to do it like that

     for(int i=0; i<desks.length; i++)
      {
        desks[i].setText("");
        rightPanel.add(desks[i]);
      }
    

    so if anyone have an idea it would be great.cheers.