简体   繁体   中英

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!

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.

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);
  }

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(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM