【问题标题】:Method Reference not working as expected [duplicate]方法参考未按预期工作[重复]
【发布时间】:2016-05-03 10:10:43
【问题描述】:

我的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();
    }   
}

这怎么能调用 METHOD 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

【问题讨论】:

    标签: java swing methods reference


    【解决方案1】:

    功能性接口是只有一个抽象方法的接口。

    方法引用不适用于第二种方法,因为WindowListener 不是functional interface;不像ActionListener 接口,它有一个抽象方法actionPerformed()

    【讨论】:

    • 实际上该方法需要一个 WindowListener - 但根本问题是相同的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多