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);
}
提前谢谢
# 1 楼答案
在匿名类中使用
this
意味着你指的是ActionListener
实例,而不是this.add(...)
只需使用add(..)
或者你可以使用MyFrame.this.add(..)
实际上,在添加组件后,您可能还需要调用
revalidate()
和repaint()
# 2 楼答案
在ActionListener中使用通用代码,这样就不需要硬编码正在使用的类
比如:
# 3 楼答案