david blaine
david blaine

Reputation: 5937

Listening and responding to events inside a Panel?

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 -

enter image description here

Upvotes: 3

Views: 2335

Answers (3)

trashgod
trashgod

Reputation: 205785

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.

Upvotes: 4

MD. Sahib Bin Mahboob
MD. Sahib Bin Mahboob

Reputation: 20514

Code is collected from Oracle JavaSE Tutorial:

public class Beeper ... implements ActionListener {
...
//where initialization occurs:
    //notice this line
    button.addActionListener(this);
...
public void actionPerformed(ActionEvent e) {
    ...//Make a beep sound...
}
}

This is how you typically register a handler right ???

What this means here ???

    button.addActionListener(this);

It means ,call current object's (which this refers) *actionPerformed method whenever a action happens with that button object. So if you pass your MainPanel's reference instead of this and your main panel has a method actionPerformed and it implements ActionListener* , whenever button fires an event , your Mainwindows's *actionPerformed** will be called.

So changed this line like this :

    button.addActionListener(RefOfMainPanel);

That's all. Yup , it's that easy :)

Upvotes: 1

Sudhanshu Umalkar
Sudhanshu Umalkar

Reputation: 4202

Create your action listeners in the MainPanel and use the same in sub panels. The source of events should let you identify the sub panel from where the event is generated.

Upvotes: 0

Related Questions