我是一名初级java程序员,尝试通过内部类实现ActionListener
。以下是一段简单的代码,我想在单击按钮时更改标签文本,但我不想对多个组件使用 getSource
,而是想使用内部类。这是我的代码:
public class InnerClasses extends JPanel {
static JFrame frame ;
static JButton button ;
static JLabel label ;
public static void main(String[] args) {
InnerClasses i= new InnerClasses();
frame= new JFrame("Inner class");
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(i);
label = new JLabel(BorderLayout.NORTH);
label.setText("I m label");
i.add(label);
button = new JButton(BorderLayout.SOUTH);
button.setText("Click me ");
button.addActionListener(new innerclass() );
i.add(button);
frame.setVisible(true);
}
class innerclass implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
label.setText("i have been changed");
}
}
现在,当我尝试将监听器注册到按钮时,它会出现错误
No enclosing instance of type InnerClasses is accessible. Must qualify the allocation with an enclosing instance of type InnerClasses (e.g. x.new A() where x is an instance of InnerClasses).
如果我做的事情不符合语法或这里有什么问题,请帮助我
最佳答案
你的内部类不是静态的,所以你不能从静态方法实例化它,一般来说,最好将内部类定义为静态,否则将为每个实例创建一个新类(而不是实例)封闭类:
static class Innerclass implements ActionListener
关于java - ActionPerfomed 方法在内部类中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17655399/