Swing:从预定线程将值传递回 UI
我有一个 Java 系统托盘 UI,需要计划数据库轮询。 生成新线程并通知 UI 的最佳方法是什么?
我是 Swing 的新手,它是线程模型。
I have a system tray UI in Java that requires a schedule database poll. What is the best method for spawning a new thread and notifying the UI?
I'm new to Swing and it's threading model.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
SwingWorker
正是为此而设计的。它允许您运行不会阻塞 GUI 的任务,然后返回一个值并在完成时更新 GUI。
Java 有一个关于如何使用 很棒的教程代码>SwingWorker。
基本上是在
doInBackground()
方法中进行数据库拉取。 并且,在done()
方法中,更新您的 GUI。SwingWorker
is the exact thing designed to do this.It allows you to run a task that won't block the GUI and then return a value and update the GUI when it is done.
Java has a great tutorial on how to use
SwingWorker
.Basically do the database pull in the
doInBackground()
method. And, in thedone()
method, update your GUI.正如 jinguy 提到的,SwingWorker 应该是您首先查看的地方。
维基百科,其中有一些有趣的示例,在您处理之前可能值得一看Java 文档。
As jinguy mentioned SwingWorker should be the first place you look at.
Wikipedia, of all places, has some interesting examples that may be good to look at before you tackle the JavaDocs.
正如 jjnguy 提到的,SwingWorker 有助于抽象出这里的复杂性,但基本上你在一个新线程中完成工作,当方法返回时,你需要在 swing 线程中更新 GUI。 如果您不使用 SwingWorker,则底层方法是 SwingUtilities(或 EventQueue).invokeLater(Runnable)。
不要更新 Swing 队列之外的任何与 Swing 相关的内容(包括模型),否则会发生不可预测的事情。 并且不要尝试保存对队列的引用并使用它,因为队列会被挂起和替换(例如,如果您打开模型对话框)。
As jjnguy mentioned, SwingWorker helps abstract away the complexity here, but basically you do the work in a new thread, and when the method comes back, you need to update the GUI in the swing thread. If you aren't using SwingWorker, the underlying method is SwingUtilities (or EventQueue) .invokeLater(Runnable).
Do not update anything Swing related (including models) outside of the swing queue, unpredictable things will happen. And don't attempt to hold a reference to the queue and use that, as queues are suspended and replaced (if for example you open a model dialog box).