How to avoid coupling the View and the Controller in Swing
Asked Answered
C

1

6

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.

Corduroys answered 21/4, 2012 at 6:56 Comment(1)
ِAlso stackoverflow.com/questions/10285582 would helpHaubergeon
I
4

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.

Iconology answered 21/4, 2012 at 7:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.