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
實際上,這個方法需要一個WindowListener - 但底層問題是一樣的。 – assylias