I have a SWING GUI class that instantiates a custom JPanel for a portion of the display. This custom class has buttons and textfields and etc. My GUI class that owns the custom JPanel also has a controller class that handles the modification of the my data models. How can I pass actions from the custom panel to it’s owner (my gui class) to handle the events?
I’ve had the thought that perhaps I can add to my constructor of the custom panel a reference to my controller class in the gui so that I can then set it as the actionListener on my buttons. Is this approach advisable? Is there a better approach?
Your
Viewcode (your customJPanel) should have aControllerfield (or some other way of obtaining your controller class). That way when you receive an action from the user – e.g. a mouse click on a button – you can callcontroller.doTheAppropriateAction(). Either pass theControllerin at construction, or use a Javabean setter pattern on it, and set it just after construction in your start-up logic (which sounds like your “GUI class”). I prefer the Javabean pattern, because GUI Editors need no-parameter constructors.You should register your
Viewas aListenerto the relevantController(orModel) classes, so that you will automatically be told when anything changes – so you canrepaint()yourComponents (or do something more advanced). That will involve setting up your owninterface(for theViewto implement) and listener handling logic in theController(orModel).Lombok PG takes the boilerplate out of the latter.
akfgives an alternative: register yourControlleras anActionListenerto yourViewcode. The advantage of that approach is that yourViewcode will not be tied to a specificController– but the disadvantage is that yourControllerwill be tied to yourViewcode. I tend to re-useControllercode for different UI implementations (e.g. Swing, GWT, JSP) so myControllers andModels are never dependent on any particularViewor atomic user action.