方法引用未按预期工作

3

我在我的class MainFrame extends JFrame类中有这两个方法:

// METHOD 1
private void connectBtnActionPerformed(ActionEvent evt) {
        controller.connectDatabase();
}

// METHOD 2
public void exitBtnActionPerformed(WindowEvent evt) {
    int confirmed = JOptionPane.showConfirmDialog(null, 
            "Are you sure you want to exit the program?", "Exit Program Message Box",
            JOptionPane.YES_NO_OPTION);

    if (confirmed == JOptionPane.YES_OPTION) {
        controller.exitApplication();
    }   
}

为什么这个可以调用方法1:

JMenuItem mntmOpenDatabase = new JMenuItem("Open a Database");
mntmOpenDatabase.addActionListener(this::connectBtnActionPerformed);

...替换为此内容:

mntmConnectToDB.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        connectBtnActionPerformed(evt);
    }
});

但在这个(class MainFrame extends JFrame 的初始化器中):

addWindowListener(this::exitBtnActionPerformed);

... 调用方法2时,无法替换以下内容:

addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent evt) {
        exitBtnActionPerformed(evt);
    }
});

相反,它给了我这个错误:
- The method addWindowListener(WindowListener) in the type Window is not applicable for the arguments 
 (this::exitBtnActionPerformed)
- The target type of this expression must be a functional interface
1个回答

2

一个函数式接口是仅有一个抽象方法的接口。

第二种方法不支持方法引用,因为WindowListener不是一个函数式接口,而ActionListener接口只有一个抽象方法actionPerformed()


1
实际上,该方法期望一个WindowListener - 但根本问题是相同的。 - assylias

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接