如何在Swing中更新JLabel? [英] How to update JLabel in Swing?
问题描述
我正在尝试使用Swing Timer,我想从一个非常简单的程序开始。我有一个带文字的窗口:你有n秒,其中n每秒从10变为0。
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.
我知道如何生成带文字的窗口。我理解Timer如何工作(它会定期启动一个动作)。但我无法弄清楚如何梳理这两件事。我应该使用它: JLabel label = new JLabel(myMessage);
然后使用计时器我需要更新myMessage变量吗?
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?
但我认为我需要强制我的窗口更新自身(显示存储在myMessage中的新值)。
But I think I need to "force" my window to "update" itself (to display a new value stored in "myMessage").
推荐答案
我建议您拨打 JLabel #setText
方法。但是,由于Swing具有非常单一的特性,您必须在所谓的事件调度线程(EDT)中更新其小部件。为此,请考虑在您的计时器代码中调用 SwingUtilities.invokeLater
或 SwingUtilities.invokeAndWait
。
这样,当你因调用setText而改变文本时,JLabel的事件将正确传播,并且label将被正确刷新。
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.
这篇关于如何在Swing中更新JLabel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!