如何在 Swing 中更新 JLabel? [英] How to update JLabel in Swing?

查看:47
本文介绍了如何在 Swing 中更新 JLabel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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.invokeLaterSwingUtilities.invokeAndWait.

这样,当您调用 setText 更改文本时,JLabel 的事件将正确传播,并且标签将正确刷新.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆