主循环和单独线程哪个更好?
场景是这样的:我有带有 JFrame 的 Java swing 应用程序。有一个文本区域,您可以在其中输入内容,然后您可以在另一个文本区域中获取搜索结果,当您选择其中一个结果时,会出现一个“下载”按钮。问题来了。当您点击“下载”时,应用程序应显示有关下载文件的完整性的信息。我使用一个名为 DownloadManager 的扩展 Thread 的类来完成此操作,该类会更新一段时间的信息。但我担心同步可能存在问题。是否有一种标准方法可以在没有线程的情况下更新此类动态信息? Java swing 类中是否有主循环或类似的东西。你怎么做?
The scenario is this: I have Java swing application with 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看看 SwingWorker:
http://download.oracle .com/javase/6/docs/api/javax/swing/SwingWorker.html
可能有更好的方法,但这就是我在下载内容和更新进度栏时用于进度栏的方法。
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.
任何更新 Java 中 GUI 的操作都应该由 GUI 事件调度线程完成。要强制方法在此线程中运行,您需要使用 SwingUtilities.invokeLater。执行其他操作可能会导致 GUI 挂起、无法更新或出现其他奇怪的情况!
这是一个很好的教程,比我更好地描述了它:
http://www.javamex。 com/tutorials/threads/invokelater.shtml
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
不,同步没有那么多问题。如果在 Swing 中使用后台线程,请考虑使用 SwingWorker< /a>.
No there are not so much problems with synchronization. If working with background threads in Swing consider to use a SwingWorker.