Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid coupling the View and the Controller in Swing

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.

like image 943
Andrew Avatar asked Apr 21 '12 06:04

Andrew


1 Answers

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.

like image 84
trashgod Avatar answered Oct 26 '22 23:10

trashgod