EventListeners and custom gui components

I have a SWING GUI class that instantiates a JPanel for a portion of the display. This custom class has buttons and text fields, etc. My GUI class, which owns a custom JPanel, also has a controller class that handles the modification of my data models. How to transfer actions from the user panel to the owner (my gui class) to handle events?

I had the thought that maybe I could add a link to my controller class in gui in my custom panel constructor, then set it as an actionListener on my buttons. Is this approach appropriate? Is there a better approach?

+6
source share
2 answers

Your View code (your custom JPanel ) should have a Controller field (or some other way to get your controller class). Thus, when you receive an action from a user — for example, clicking a button — you can call controller.doTheAppropriateAction() . Either pass the Controller to the construct, or use the Javabean setter pattern on it, and install it immediately after building in your startup logic (which sounds like your "GUI class"). I prefer the Javabean template because GUI editors need parameterless constructors.

You must register your View as a Listener in the appropriate Controller (or Model ) classes, so that you will be automatically informed when something changes so that you can repaint() use Component (or do something more advanced). This will be related to setting up your own interface (for View to implement) and listener processing logic in the Controller (or Model ).

Lombok PG deduces a template from the last.

akf provides an alternative: register the Controller as an ActionListener in your View code. The advantage of this approach is that your View code View not bound to a specific Controller , but the disadvantage is that your Controller will be bound to your View code. I tend to reuse Controller code for various user interface implementations (e.g. Swing, GWT, JSP), so my Controller and Model never dependent on any specific View or atomic user actions.

+4
source

You can pass the link to your parent GUI as an ActionListener to your custom dashboard. Your user panel can then register your ActionListener additional parent class with all of your buttons, etc.

Your parent class will then be notified of each action.

+2
source

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


All Articles