处理外部类的JFrame组件的最佳方法 [英] Best way to handle JFrame components from outside class

查看:115
本文介绍了处理外部类的JFrame组件的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个调用多种方法的Swing应用程序,初始化不同的类. 我也有多个线程,它们在其中处理中间结果.我的要求是在一些标签和文本框中即时显示中间数据.

请帮助我以下哪种方法在内存和性能方面是最好的.

  1. 我可以为所有标签和文本框设置setter方法.这样我就可以使用该swing类对象来调用这些方法,但在那种情况下,我需要将swing类对象传递给每个我想将数据设置为标签的类.
  2. 另一种方法是,我可以创建我的swing类的公共静态对象,并且在需要设置标签文本时可以从任何类调用它.

第一个方法会产生更多开销,因为我需要将Swing类对象传递给其他类.

第二种方法是最简单的方法,但是由于此应用程序包含线程,因此创建静态对象可能会造成混乱.

我只想知道要去哪一个,为什么?

否则,如果有人从事过一些复杂的swing应用开发工作,那么您是如何处理此类问题的呢?

解决方案

示例是您在多线程上下文.为了方便起见,模型和视图紧密耦合:每个工作线程都收到对其应更新的标签的引用.另一种选择是松散耦合:每个视图注册以监听模型,该模型使用观察者模式通知所有注册的监听器. /p>

这个简单的示例使用两种方法:

  • 紧密耦合:工人在封闭范围内获得对其目标标签的引用.

  • 松散耦合:封闭的视图注册了PropertyChangeListener,该模型用于通过setProgress()向视图发出信号.

您需要确定在您的应用程序中哪个重要.我同意@JB Nizet对第二种方法的评论.

I was developing a swing application which calls multiple methods & initializes different classes. Also I have multiple threads in which they process intermediate results. My requirement is to display that intermediate data on some labels and text boxes on the fly.

Please help me which of the below approach is best in terms of memory and performance.

  1. I can have setter methods for all my labels and text boxes. So that I can call these methods using that swing class object but in that case I need to pass the swing class object to every class wherever I want to set the data to labels.
  2. Another way is I can create public static object of my swing class and I would call it from any class whenever I need to set the label text.

First method creates more overhead as I need to pass the my Swing class object to other classes.

Second method is easiest way but creating static objects might create confusion as this application contains threads.

I just want to know which one to go for and why?

Otherwise if anybody have worked on some complex swing app development - how did you manage these kind of issues?

解决方案

This example is typical of your first approach in a multi-threaded context. For expedience, the model and view are tightly coupled: each worker thread receives a reference to the label it should update. The alternative is loose coupling: each view registers to listen to the model, which notifies all registered listeners using the observer pattern.

This simpler example uses both approaches:

  • Tight coupling: The worker obtains a reference to its target label in an enclosing scope.

  • Loose coupling: The enclosing view registers a PropertyChangeListener, which the model uses to signal the view via setProgress().

You'll need to decide which is important in your application. I agree with @JB Nizet's comment about the second approach.

这篇关于处理外部类的JFrame组件的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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