java 如何重置 JLabel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9872714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reset JLabel
提问by Kiril
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
我正在尝试重置一组 JLabel。标签顶部有图像,因此当我按下按钮时,标签应该被重置。我试着那样做
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.
所以如果有人有想法,那就太好了。干杯。
回答by Steve McLeod
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("");
}
});
回答by GETah
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("");
}
回答by mKorbel
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("");
}
}
}