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 View
code (your custom JPanel
) should have a Controller
field (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 call controller.doTheAppropriateAction()
. Either pass the Controller
in 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 View
as a Listener
to the relevant Controller
(or Model
) classes, so that you will automatically be told when anything changes - so you can repaint()
your Component
s (or do something more advanced). That will involve setting up your own interface
(for the View
to implement) and listener handling logic in the Controller
(or Model
).
Lombok PG takes the boilerplate out of the latter.
akf
gives an alternative: register your Controller
as an ActionListener
to your View
code. The advantage of that approach is that your View
code will not be tied to a specific Controller
- but the disadvantage is that your Controller
will be tied to your View
code. I tend to re-use Controller
code for different UI implementations (e.g. Swing, GWT, JSP) so my Controller
s and Model
s are never dependent on any particular View
or atomic user action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With