Update JLabel from another thread

隐身守侯 提交于 2019-12-01 12:37:46

问题


Dear guys, I'm having swing related problem. 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. This JLabel's text is updated randomly through a timer object, that instantiates a TimerTask every 50 ms using the scheduleAtFixedRate method. 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. 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. What would the problem be?


回答1:


The problem is that you access swing components in other threads than the Event Dispatch Thread (EDT). 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.




回答2:


Instead of java.util.Timer, javax.swing.Timer may be more convenient, as seen in this example.



来源:https://stackoverflow.com/questions/5895481/update-jlabel-from-another-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!