Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing - calling events from inside panel

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?

like image 977
zaharpopov Avatar asked Jun 01 '11 13:06

zaharpopov


2 Answers

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
      }
  });
like image 155
Vincent Ramdhanie Avatar answered Sep 20 '22 00:09

Vincent Ramdhanie


Have a look on this tutorial for using SwingWorker.

like image 29
oliholz Avatar answered Sep 19 '22 00:09

oliholz