如何避免在Swing中耦合View和Controller [英] How to avoid coupling the View and the Controller in Swing

查看:187
本文介绍了如何避免在Swing中耦合View和Controller的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了一个问题,试图在Swing中实现模型 - 视图 - 控制器。



我有一个由子面板组成的GUI类,以及那些子板由其他子板组成。现在,在其中一个子子面板中有一个JButton。在这个JButton的ActionListener中,我想在控制器中调用一个方法。为了做到这一点,我需要将控制器深入GUI的内部传递到JButton所在的子子面板。然后在这个子子面板中,我需要将一个ActionListener附加到JButton并通过调用我想在控制器中调用的方法来填充actionPerformed()。



<我确定你们都看到了这个问题。有没有什么好方法可以避免将控制器深深地传递到GUI的内部。



我唯一想到的是让控制器成为一个单独的控制器,将它与视图分离,但是我听说单身人士通常是邪恶的。



对此事的任何建议都会非常感激。提前致谢!

解决方案

让控制器监听到视图,而不是传入对控制器的引用,正如间接关联所示,此处。添加 PropertyChangeListener ,如此处所示,非常适用于此。当视图需要调用控制器时,它只需调用 firePropertyChange()



更方便的方法是为控制器提供某些操作的单独视图,例如 reset()方法>这里


I have recently come across a problem trying to implement Model-View-Controller in Swing.

I have a GUI class which consists of sub-panels, and those sub-panels consist of other sub-panels. Now in one of these sub-sub panels there is a JButton. In the ActionListener for this JButton I want to call a method in the controller. In order to do this I would need to pass the controller deep into the bowels of the GUI to the sub-sub panel where the JButton resides. Then in this sub-sub panel I would need to attach an ActionListener to the JButton and fill out the actionPerformed() by calling the method that I wanted to call in the controller.

I'm sure you all see the problem. Is there any good way of avoiding passing the controller deep into the bowels of the GUI.

My only thought was to make the controller a singleton to decouple it from the view, but I have heard that singleton's are usually evil.

Any advice on this matter would be most appreciated. Thanks in advance!

解决方案

Instead of passing in a reference to the controller, let the controller listen to the view, as suggested by the indirect association pictured here. Adding a PropertyChangeListener, illustrated here, is ideal for this. When the view needs to call upon the controller, it simply invokes firePropertyChange().

A more expedient approach is to give the controller a separate view for certain operations such as the reset() method shown here.

这篇关于如何避免在Swing中耦合View和Controller的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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