How to reset JLabel

拜拜、爱过 提交于 2019-12-24 03:35:09

问题


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.


回答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("");
         } 
    }
}



回答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("");
   }
});



回答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("");
 }


来源:https://stackoverflow.com/questions/9872714/how-to-reset-jlabel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!