如何在 Swing 中更新 JLabel?

编程入门 行业动态 更新时间:2024-10-23 03:28:56
本文介绍了如何在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-28 18:15:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/737027.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Swing   JLabel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!