java 如何在 Swing 中更新 JLabel?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2477155/
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 update JLabel in Swing?
提问by Roman
I am trying to use Swing Timer and I wanted to start from a very simple program. I have a window with text: "You have n seconds", where n changes from 10 to 0 every second.
我正在尝试使用 Swing Timer,我想从一个非常简单的程序开始。我有一个带有文本的窗口:“您有 n 秒”,其中 n 每秒从 10 变为 0。
I know how to generate a window with text. And I understand how Timer works (it starts an action periodically). But I cannot figure out how to combing this two things. Should I use that: JLabel label = new JLabel(myMessage);and then with timer I need to update the "myMessage" variable?
我知道如何用文本生成一个窗口。而且我了解 Timer 的工作原理(它会定期启动一个动作)。但我无法弄清楚如何将这两件事结合起来。我应该使用它:JLabel label = new JLabel(myMessage);然后使用计时器更新“myMessage”变量吗?
But I think I need to "force" my window to "update" itself (to display a new value stored in "myMessage").
但我认为我需要“强制”我的窗口“更新”自身(以显示存储在“myMessage”中的新值)。
回答by Riduidel
I suggest you to call the JLabel#setTextmethod each time content is updated. however, due to the very monothread nature of Swing, you have to update its widgets in the so-called Event Dispatch Thread (EDT). To do so, consider calling SwingUtilities.invokeLateror SwingUtilities.invokeAndWaitin your timer code.
我建议您JLabel#setText每次更新内容时都调用该方法。然而,由于 Swing 的单线程特性,您必须在所谓的事件调度线程 (EDT) 中更新它的小部件。为此,请考虑在您的计时器代码中调用SwingUtilities.invokeLater或SwingUtilities.invokeAndWait。
This way, when text will be changed due to your call of setText, events of JLabel will propagate correctly, and label will be correctly refreshed.
这样,当您调用 setText 更改文本时,JLabel 的事件将正确传播,并且标签将正确刷新。
回答by ibrahimyilmaz
Hi bro use observer pattern . That is ,your ui class sould be listener of your timer structure.When your variable changes ,invoke the listeners of your timer which is your ui class.
嗨兄弟使用观察者模式。也就是说,你的 ui 类应该是你的计时器结构的监听器。当你的变量发生变化时,调用你的计时器的监听器,它是你的 ui 类。
//your observer class
update(Object obj){
label.setText(obj.toString());
}
...
//your observable class
//when timer changes varible's value you should call invokeListeners()
invokeListener(){
for(Listener listener :listeners)
listener.update(getSecond());
}
I dont know your class and structure.But i used this solution in one of my assignments.
我不知道你的班级和结构。但我在我的一项作业中使用了这个解决方案。

