How to avoid connecting View and controller in Swing

I recently ran into a problem trying to implement Model-View-Controller in Swing .

I have a GUI class that consists of sub-panels, and these sub-panels are composed of other sub-panels. Now one of these subsections has 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 transfer the controller deep into the bowels of the GUI to the sub-sub panel where JButton is located. Then in this subitem I needed to attach an ActionListener to a JButton and populate actionPerformed() by calling the method that I wanted to call in the controller.

I am sure you all see the problem. Is there a good way to prevent the controller from penetrating deep into the bowels of the GUI.

My only thought was to make the controller a singleton to separate it from the view, but I heard that the singleton is usually evil.

Any advice on this would be most valuable.

+6
source share
1 answer

Instead of passing a reference to the controller, let the controller listen for the view, as suggested by the indirect association depicted here . The addition of the PropertyChangeListener illustrated here is ideal for this. When the view should call the controller, it simply calls firePropertyChange() .

A more appropriate approach is to provide the controller with a separate view for certain operations, such as the reset() method shown here .

+4
source

Source: https://habr.com/ru/post/913771/


All Articles