如何修复 java 中的动作侦听器错误?

How to fix error in action listener in java?

所以我的代码有一个错误,我不知道为什么会这样,因为我听从了老师的指示。每当我在 addActionListener 中添加参数时,我都会收到此错误。

这是我的全部代码

import java.awt.FlowLayout;
import java.awt.event.*;
import java.sql.Date;
import javax.swing.*;

public class DateFrameButton  implements ActionListener{

    public static void main(String[] args) {
        final int FIELD_WIDTH = 20;
        JFrame frame = new JFrame();
        JButton dateButton = new JButton("Date");
        JTextField textField = new JTextField(FIELD_WIDTH);
        String dateAndTime = new Date(FIELD_WIDTH).toString();
        
        
        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                textField.setText(dateAndTime);
            }
        };
        
        dateButton.addActionListener(listener);
        
        frame.add(dateButton);
        frame.add(textField);
        frame.setLayout(new FlowLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        // TODO Auto-generated method stub
        
    }

}

这是我收到错误的地方:

dateButton.addActionListener(listener);

错误说

The method addActionListener(java.awt.event.ActionListener) in the type AbstractButton is not applicable for the arguments (ActionListener)

而且我真的不知道为什么会出现该错误

dateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent event) {
                textField.setText(dateAndTime);
            }
         });

按钮对传递的参数感到困惑。是你实现的ActionListenerclass吗?创建的实例?它期望 java.awt.event.ActionListener, 但收到 ActionListener.

不要创建 ActionListener 的实例,只需确保传递 java.awt.event.ActionListener