有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从匿名ActionListener访问JFrame,以便在框架中添加面板?

如果点击某个按钮,我想在一个框架中添加一个JPanel,但我不知道如何从匿名ActionListener管理它。以下是代码:

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

提前谢谢


共 (3) 个答案

  1. # 1 楼答案

    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意味着你指的是ActionListener实例,而不是this.add(...)只需使用add(..)或者你可以使用MyFrame.this.add(..)

    实际上,在添加组件后,您可能还需要调用revalidate()repaint()

  2. # 2 楼答案

    在ActionListener中使用通用代码,这样就不需要硬编码正在使用的类

    比如:

    JButton button = (JButton)event.getSource();
    Window window = SwingUtilities.windowForCompnent( button );
    window.add(...);
    
  3. # 3 楼答案

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