Swing calls from the inside panel

I have a simple Swing GUI with a main window JFrame, and its main panel is JPanel. The panel has several buttons that you can click to create events.

I want these events to affect the data stored in JFrame, because this is my main application - it has several queues for threads, open threads, etc.

So, how do I get my button in a panel to call callbacks in my parent frame? What is best for Java / Swing?

+5
source share
4 answers

To call methods in the parent frame, you need a reference to the parent frame. Therefore, your JPanel constructor can be declared as follows:

 public MyPanel(MyFrame frame){
    super();
    this.frame = frame;
    //the rest of your code
}

And in JFrame, you call this constructor as follows:

  panel = new MyPanel(this);//this refers to your JFrame

In the case when the handlers attached to your buttons now have access to the frame and can use various methods if necessary.

  button1.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
           //do some stuff
           frame.someMethod();//invoke method on frame
           //do more stuff
      }
  });
+3
source

Use the addActionListener method on the desired buttons that define the class that implements the ActionListener.

ActionListenerClass actionListenerObject = new actionListenerClass();
JButton b = new JButton("Button");
b.addActionListener(actionListenerObject);

public class ActionListenerClass implements ActionListener(){
 //or better : actionListenerClass extends AbstractAction
      public void actionPerformed(ActionEvent e) {
      }
}

EDIT:

Yes I know that. But action listener I want to be in the parent JFrame class - this is a problem

then extends the JFrame class, creating a new derived class that implements the required interface.

+1
source

SwingWorker.

+1

ActionListener , JFrame ( ):

class MyPanelClass {
    public MyPanelClass(ActionListener al)
    {
        //...
        JButton myButton = new JButton("Button");
        myButton.addActionListener(al);
        //...
    }
}

class MainClass extends JFrame implements ActionListener {
    public void someMethod() {
        MyPanelClass mpc = new MyPanelClass(this);
    }

    @Override
    public void ActionPerformed(ActionEvent ev) {
        // your implementation
    }
}
+1

All Articles