Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EventListeners and custom gui components

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?

like image 428
Nicholas Hazen Avatar asked Aug 03 '12 23:08

Nicholas Hazen


1 Answers

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 Components (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 Controllers and Models are never dependent on any particular View or atomic user action.

like image 110
fommil Avatar answered Oct 16 '22 08:10

fommil