sve*_*cax 4 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);
}
Run Code Online (Sandbox Code Playgroud)
先感谢您!
在这里,我想将面板添加到框架中:this.add(panel),但我不知道该怎么写。在这种情况下,“ this”是指ActionListener,而不是框架,所以我想知道要写什么而不是“ this”,以便引用框架
而不是this.add(...)仅仅使用add(..)或可以使用MyFrame.this.add(..) 原因this,匿名类中的use 意味着您正在引用ActionListener实例。
其实你可能还需要打电话revalidate()和repaint() 后添加组件。
在 ActionListener 中使用通用代码,这样您就不需要对您正在使用的类进行硬编码。
就像是:
JButton button = (JButton)event.getSource();
Window window = SwingUtilities.windowForCompnent( button );
window.add(...);
Run Code Online (Sandbox Code Playgroud)