开发者

Swing - calling events from inside panel

开发者 https://www.devze.com 2023-03-09 23:06 出处:网络
I have simple Swing GUI with main window JFrame and its main panel derive from JPanel. The panel has some buttons that can be clicked and 开发者_开发技巧generate events.

I have simple Swing GUI with main window JFrame and its main panel derive from JPanel. The panel has some buttons that can be clicked and 开发者_开发技巧generate events.

I want these events affect data stored in JFrame because it is my main application - it has some queues for thread, open streams and so on.

So how do I make my button in panel invoke callbacks in its parent frame? What is best practice of this for Java/Swing?


To invoke methods in the parent frame you need a reference to the parent frame. So your JPanel's constructor can be declared like this:

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

And in the JFrame you invoke this constructor like this:

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

In the event handlers attached to your buttons you now have access to the frame and can invoke the various methods as needed.

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


Have a look on this tutorial for using SwingWorker.


Use addActionListener method on desired buttons specifying the class implementing 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 this. But the action listener I want to be in parent JFrame class - this is the problem

then extends JFrame class making the new derived class implementing the desired interface.


You can implement the ActionListener in your class that has the JFrame (or extends it):

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
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号