简体   繁体   English

从另一个线程更新 JLabel

[英]Update JLabel from another thread

Dear guys, I'm having swing related problem.亲爱的伙计们,我遇到了与 swing 相关的问题。 I cannot share the code since it's against the company policy, so I will try my best to explain the problem.我不能分享代码,因为它违反了公司政策,所以我会尽力解释这个问题。

In short, I have created a class that extends JWindow that contains a JLabel.简而言之,我创建了一个 class,它扩展了包含 JLabel 的 JWindow。 This JLabel's text is updated randomly through a timer object, that instantiates a TimerTask every 50 ms using the scheduleAtFixedRate method.此 JLabel 的文本通过计时器 object 随机更新,该计时器使用 scheduleAtFixedRate 方法每 50 毫秒实例化一个 TimerTask。 The values in the JLabel are retrieved by calling a method in a separate thread (let's call it transmission thread) that handles transmitting data to a certain device. JLabel 中的值是通过在一个单独的线程(我们称之为传输线程)中调用一个方法来检索的,该线程处理将数据传输到某个设备。 The problem is that the JWindow appears on the screen with no content whatsoever till the transmission to the device is over, then I'd be getting the last result of the transmission thread.问题是 JWindow 出现在屏幕上没有任何内容,直到传输到设备结束,然后我会得到传输线程的最后一个结果。 What would the problem be?会有什么问题?

Instead of java.util.Timer , javax.swing.Timer may be more convenient, as seen in this example .代替java.util.Timerjavax.swing.Timer可能更方便,如本例所示

The problem is that you access swing components in other threads than the Event Dispatch Thread (EDT).问题是您在除事件调度线程 (EDT) 之外的其他线程中访问 swing 组件。 This is forbidden.这是禁止的。

The javadoc of every swing componenthas a link to this page: http://download.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#threading , where the threading policy is explained in details. The javadoc of every swing componenthas a link to this page: http://download.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#threading , where the threading policy is explained in details .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM