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

时间:2013-12-28 20:15:11

标签: java swing actionlistener

如果单击某个按钮并且我不知道如何从匿名ActionListener管理它,我想在框架中添加JPanel。这是代码:

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 个答案:

答案 0 :(得分:5)

  

这里我想将面板添加到框架:this.add(面板),但我没有   知道怎么写。 在这些情况下,“this”指的是ActionListener,   不要框架,所以我想知道写什么而不是“这个”   为了引用框架

而不是this.add(...)只使用add(..)或者您可以使用MyFrame.this.add(..)因为在匿名类中使用this意味着您指的是ActionListener实例。< / p>

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

答案 1 :(得分: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);
  }

答案 2 :(得分:3)

ActionListener中的用户通用代码,因此您无需对正在使用的类进行硬编码。

类似的东西:

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