Listening and responding to events inside a Panel?

java, swing

Solution

You may be looking for the observer pattern. Java Swing programs may use any of several ways to implement the pattern; some examples are cited here. Because a component may accept an arbitrary number of listeners, one important heuristic is to look for an existing sub-panel component to which the parent can listen. In the particular case of sub-panels, it may also be possible to forward events to a parent's listener, as suggested here.

Problem

I have a MainPanel. It contains SubPanel1, SubPanel2 etc. SubPanel can have any combination of JComponents like buttons, radio buttons, text boxes etc. One SubPanel may or may not be the same as another. How do I make the MainPanel listen and respond to the actions taking place inside the SubPanels ? Please show me some good example with commented code which teaches me how to do this. Photo -

Original source

Related problems