gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:21:42 25 4
gpt4 key购买 nike

如果单击某个按钮,我想在框架中添加一个 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);
}

提前致谢!

最佳答案

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(...) 只需使用 add(..) 或者您可以使用 MyFrame.this.add(..) 因为在匿名类中使用 this 意味着您指的是 ActionListener 实例。

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

关于java - 如何从匿名 ActionListener 访问 JFrame 以在框架中添加面板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20818927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com