Swing Component Event Handlers

I have a menu class called Menu Defining JFrame, this class creates two JPanels that contain text boxes and buttons. Each JPanel extension class has a private inner class that handles button events.

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

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

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



source to share

2 answers

JPanels and virtually all Swing components have support for changing properties, so you can easily add a PropertyChangeListener to any component and listen for state changes. Just make sure that in the code whose state changes to being called firePropertyChange(...)

after the state changes.



You can always add listeners to components (like ActionListener

instances) and handle them.

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



All Articles