方法参考不按预期工作

时间:2016-01-26 18:05:14

标签: java swing methods reference

我的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 个答案:

答案 0 :(得分:2)

功能性界面是一个只有一个抽象方法的界面。

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