开发者

Which is better - mainloop or separate threads?

The scenario is this: I have Java swing application wi开发者_高级运维th JFrame. There is textarea where you can type things, then you get the search results in another textarea and when you select one of the results, there is a button "Download". And here comes the problem. When you hit "Download" the application should display information about the completness of the downloaded files. I've do this with a class extending Thread called DownloadManager which updates the information on a period of time. However I'm concerned that there may be problems with synchronization. Is there a standard way to update such dynamic info without threads? Is there a mainloop or something like this in Java swing classes. How do you do it?


Have a look at SwingWorker:

http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html

There may be better ways but that's what I used for my progress bar when downloading things and updating progress bars.


Anything that updates the GUI in Java should be done by the GUI event dispatch thread. To force a method to be run in this thread, you need to use the SwingUtilities.invokeLater. Doing anything else could potentially cause your GUI to hang, not update, or other strangeness!

This is a good tutorial that describes it better than I did:

http://www.javamex.com/tutorials/threads/invokelater.shtml


No there are not so much problems with synchronization. If working with background threads in Swing consider to use a SwingWorker.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜