Swing应用程序多线程设计模式和最佳做法 [英] Swing application multithread design patterns and best practices

查看:305
本文介绍了Swing应用程序多线程设计模式和最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读很多的答案和问题,但我从来没有问过。



我的问题是关于Swing应用程序中的设计模式和最佳做法。假设你有一个带有JLabel和另一个类(不是之前的内部类)的GUI类的Swing应用程序,它扩展了Thread并执行了一些网络操作(基本上是它定期从Web API获取资源,以检查给定值是否出现)。



当第二个类获取某个值时,我需要更新JLabel的粉丝班我完全知道这应该在EDT中使用 invokeLater()完成,我的问题是如何处理从后台线程到JLabel.setText()方法的访问。



据我所知,我看到三个解决方案:




  • 提供在GUI类中的静态吸收器,并调用它在Thread类中 c $ s $ S $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $内部调用 SwingUtilities.invokeLater()并从Thread类访问该方法(说MyGui.updateTheLabel())的GUI类

  • 将JLabel的引用传递给Thread构造函数,并使用该引用使用SwingUtilities.invokeLater()更新标签



哪个这个解决方案比较好吗?是否有特定的设计模式旨在解决这个问题。我发现它很难把SwingUtilities.invokeLater()在任何地方我想要更新GUI或创建静态吸引器。



谢谢:)

解决方案

网络线程不应该知道JLabel。其职责是从网络加载一些数据。在屏幕上显示数据是另一个任务,应该使用特殊的UI类。该类应该有一些方法,例如( update(byte []),内部调用 invokeLater UI类应该在创建时传递给网络线程,该线程应定期调用 update 方法。


I've been reading a lot of SO answer and questions but I never asked anything before.

My question is about desing patterns and best practices in Swing application.

Suppose you have a Swing application with a GUI class with a JLabel and another class (not an inner class of the previous) which extends Thread and perform some network operations (basically it periodically fetch resources from a web API to check if a given value appear).

When a certain value is fetched by the second class I need to update the JLabel of the firt class. I'm perfectly aware this should be done in the EDT using invokeLater(), my question is how to handle the access from the background Thread to the JLabel.setText() method.

As far as I know I see three solution:

  • provide a static getter in the GUI class and call it insite a SwingUtilities.invokeLater() in the Thread class
  • provide a static method inside the GUI class which internally calls SwingUtilities.invokeLater() and access that method (say MyGui.updateTheLabel()) from the Thread class
  • passing a reference of the JLabel to the Thread constructor and use that reference to update the label with SwingUtilities.invokeLater()

Which one of this solution is better? Are there particular design patterns meant to solve this issue. I find it ugly to put SwingUtilities.invokeLater() everywhere I want to update the GUI or creating static getters around.

Thank you :)

解决方案

The networking thread should not know about JLabel. Its duty is to load some data from network. Exposing that data on a screen is another task, and should be made with a special UI class. That class should have some method like (update(byte[]), which internally calls invokeLater. An instance of that UI class should be passed to the networking thread at creation time, and that thread should periodically call update method.

这篇关于Swing应用程序多线程设计模式和最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆