GUI /应用程序通信
处理 GUI/内部应用程序通信的最佳方法是什么?我有许多底层线程处理数据,并且想将它们的输出发布到图形用户界面。
我是否应该有某种由我的所有可运行对象拥有的处理程序对象,然后将它们发布到它,以便它可以处理到 gui 的输出?
What is the best way to handle GUi/ internal application communication. I have many underlying threads processing data, and would like to post their output to the gui.
Should I have some kind of handler object that is owned by all my runnables, and then have them post to it, so it can handle the output to the gui?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常使用观察者模式来进行这种通信。所以基本上你的线程类实现了一个公共接口(addObserver()),使它们成为可观察的,并且你的GUI控制器/视图实现了观察者接口(fireNewEvent())。如果线程产生了某种新内容,它会调用观察者上的方法。根据您的项目,要呈现的信息可以推送给观察者(例如 fireNewEvent(Event e)),或者观察者可以自行访问信息(拉取) 。基本上,这是您的想法加上通知多个观察者(如果需要)的灵活性。
I usually use an observer pattern for that kind of communication. So basically your thread classes implement a common interface (addObserver()) making them observables and your GUI controller/view implements the observer interface (fireNewEvent()) . If a thread has produced some kind of new content, it calls a method on the observer. Depending on your project the information to be presented can be pushed to the observer (e.g. fireNewEvent(Event e)) or the observer can access the information on its own (pull). Basically this is your idea plus the flexibility of notifying more than one observer (if needed).
如果您使用线程来避免在执行长任务时冻结 UI,则 SwingWorker 可以帮助您。
If you're using threads to avoid freezing the UI while executing long tasks, SwingWorker can help you.