Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a JFrame from anonymous ActionListener for adding a panel in frame?

I want to add a JPanel in a frame if a certain button is clicked and I don't know how to manage that from an anonymous ActionListener. Here is the code:

public class MyFrame extends JFrame {
   JPanel panel;
   JButton button;
   public MyFrame() {
      button = new JButton("Add panel");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent event) {
            panel = new JPanel();
            //here I want to add the panel to frame: this.add(panel), but I don't know
            //how to write that. In these case "this" refers to ActionListener, not to
            //frame, so I want to know what to write instead of "this" in order to
            //refer to the frame
         }
      }
      this.add(button);
  }

Thank you in advance!

like image 273
svecax Avatar asked Dec 11 '22 08:12

svecax


1 Answers

here I want to add the panel to frame: this.add(panel), but I don't know how to write that. In these case "this" refers to ActionListener, not to frame, so I want to know what to write instead of "this" in order to refer to the frame

Instead of this.add(...) just use add(..) or you can use MyFrame.this.add(..) cause using this in anonymous class means that you are referring to ActionListener instance.

Actually you may also have to call revalidate() and repaint() after you add a component.

like image 69
nachokk Avatar answered Dec 13 '22 22:12

nachokk