svecax
svecax

Reputation: 379

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!

Upvotes: 5

Views: 5563

Answers (3)

nachokk
nachokk

Reputation: 14413

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.

Upvotes: 6

camickr
camickr

Reputation: 324108

User generic code in your ActionListener so you don't need to hardcode the class that you are using.

Something like:

JButton button = (JButton)event.getSource();
Window window = SwingUtilities.windowForCompnent( button );
window.add(...);

Upvotes: 5

Meno Hochschild
Meno Hochschild

Reputation: 44061

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
            MyFrame.this.add(panel);
         }
      }
      this.add(button);
  }

Upvotes: 4

Related Questions