Java:ActionListener 错误

标签 java jframe actionlistener

我有这段代码,它使用一个文本字段,程序将从该文本字段接收用户的输入,因此我尝试将一个 ActionListener 添加到我的文本字段输入中。但是,当我编译时,我收到此错误: Quiz.java:5: error: Quiz is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener public class Quiz implements ActionListener {

代码:

public class Quiz implements ActionListener {

private static Label lblInput;         
private static TextField tfInput;  
private static String cityIn;       

   public void europe() {
      JFrame frame = new JFrame();      
      frame.setLayout(null);

      lblInput = new Label("Skriv in huvudstaden i : "); // Construct Label
      lblInput.setBounds(40,30,300,40);
      frame.add(lblInput);

      tfInput = new TextField(10);
      tfInput.setBounds(40,70,300,40);
      frame.add(tfInput);

      tfInput.addActionListener(this);

      frame.setTitle("Europa"); 
      frame.setSize(375, 150);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);

   }


}

最佳答案

您必须重写 actionPerformed(ActionEvent e) 方法:

public class Quiz implements ActionListener {

    private static Label lblInput;
    private static TextField tfInput;
    private static String cityIn;

    public void europe() {
        ....
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // Your code
    }
}

编辑:(第二种方式)

您可以使用自定义 ActionListener 处理文本字段上的事件:

public class Quiz implements ActionListener {

    private static Label lblInput;
    private static TextField tfInput;
    private static String cityIn;

    public void europe() {
        ....
        tfInput.addActionListener(new CustomActionListener());
        ...
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // Your code
    }
}

class CustomActionListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        // Your code
    }
}

关于Java:ActionListener 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33725126/

相关文章:

Java ActionListener - 更改 actionPerformed 中的变量

java - JPanel 中的计时器

Java EE 移动网站

java - 对多个列表中的元素进行分组

java - 无法使用 mouselistener 中的 JFrame 方法

java - 如何记住从其他框架选中的复选框

java - 将变量传递给 ActionListener

java - Spring MVC/hibernate 表单验证,不返回表单

java - JAXB/MOXy 对多个属性使用相同的实体类型

java - 设计一个窗体来调用另一个窗体,并且在子窗体关闭后不退出