"The method addActionListener(ActionListener) in the type AbstractButton is not applicable for the arguments" 错误

"The method addActionListener(ActionListener) in the type AbstractButton is not applicable for the arguments" error

我想创建一个 JFrame,当您单击 JButton 时,它会在控制台上打印出来:"It works!!"。下面是代码:

import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;

public class CurrentlyMajorCodesCompiler extends JFrame {

public static void main (String args[]) {
CurrentlyMajorCodes CMC = new CurrentlyMajorCodes();

CMC.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

public class CurrentlyMajorCodes extends JFrame {

private JButton ClickSpeedTest;
private tensCPS TCPS;

public CurrentlyMajorCodes () {
    super("Major Code Compiler");
    setLayout(new FlowLayout());

    ClickSpeedTest = new JButton("Click Speed Test");
    add(ClickSpeedTest);

    ClickSpeedTest.addActionListener(new MouseAdapter () {
        public void mouseClicked (MouseEvent event) {
            System.out.println("It works!!");
        }
    });

    setSize(250, 250);
    setVisible(true);
}
}

但是,在:ClickSpeedTest.addActionListener,它给我一个错误提示:

The method addActionListener(ActionListener) in the type 
    AbstractButton is not applicable for 
    the arguments (new MouseAdapter(){})`

我不明白它试图传达什么,因为我从未在代码中使用过 AbstractButton,甚至不知道它是什么。有人可以帮忙吗?

MouseListener 不同于ActionListener。您需要使用后面的

ClickSpeedTest.addActionListener(new ActionListener () {
    public void actionPerformed (ActionEvent event) {
        System.out.println("It works!!");
    }
});

方法addActionListener() in class AbstractButton takes a single parameter, namely an instance of a class that implements interface ActionListener。 Class JButton 扩展了 AbstractButton 因此继承了这个方法。

现在看classMouseAdapter。您会看到它 没有 实现接口 ActionListener,因此不适合作为方法 addActionListener().

的参数

对于您问题中描述的要求,我建议创建您自己的接口实现 ActionListener。以下类似于您发布的代码并使用匿名内部 class 实现接口 ActionListener:

ClickSpeedTest.addActionListener(new ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent event) {
        System.out.println("It works!!");
    }
});

请注意,无论是通过鼠标、键盘还是通过 java 代码,只要按钮 ClickSpeedTest 被激活,就会调用上述 actionPerformed() 方法。 (参考classAbstractButton中的方法doClick()。)

如果您使用的是 Java 8 或更高版本,那么 ActionListenerfunctional interface, i.e. an interface that contains precisely one abstract method and hence you can implement it using a lambda expression 这意味着您也可以使用以下代码:

ClickSpeedTest.addActionListener(e -> System.out.println("It works!!"));