Reputation: 272
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.
Upvotes: 2
Views: 12476
Reputation: 109813
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("");
}
}
}
Upvotes: 4
Reputation: 52448
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("");
}
});
Upvotes: 6
Reputation: 21419
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("");
}
Upvotes: 5