Nicholas Hazen
Nicholas Hazen

Reputation: 1315

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?

Upvotes: 6

Views: 155

Answers (2)

fommil
fommil

Reputation: 5875

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.

Upvotes: 4

akf
akf

Reputation: 39485

You can pass a reference to your parent GUI as an ActionListener to your custom panel. Your custom panel can then register your ActionListener-implementing parent class with all of your buttons, etc.

Your parent class would then get notified on each action.

Upvotes: 2

Related Questions