lilroo
lilroo

Reputation: 3198

Swing Component Event Handlers

I have a menu class called Menu wich defines a JFrame, this class instantiates two JPanel objects which contain text fields and buttons. There is a private inner class inside each JPanel extending class which handles the events triggered by pressing the buttons.

I want to know if there is a way for the Menu class to detect the triggered events from the buttons inside the JPanels.

Could you add a listener to a JPanel in the Menu class and do something like this? :

if(event.getSource() == panel.getButton1()){ 
    //do button1 code 
} 

Upvotes: 3

Views: 264

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285460

JPanels and in fact all Swing components have property change support, and so you could easily add a PropertyChangeListener to any Component and listen for state changes. Just be sure that in the code whose state is changing to call firePropertyChange(...) after the state changes.

Upvotes: 3

Thomas
Thomas

Reputation: 88757

You can always add listeners to components (e.g. ActionListener instances) and handle them.

In terms of design you should consider splitting menu/layout and event handling, i.e. use a separate controller to listen for events and handle them.

Upvotes: 1

Related Questions