2016-01-26 110 views
3

我有这2种方法在我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 

回答

2

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

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

+1

实际上,这个方法需要一个WindowListener - 但底层问题是一样的。 – assylias