3

I have these 2 methods in my class MainFrame extends JFrame class:

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

How come this works to call METHOD 1:

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

... to replace this:

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

But this (in class MainFrame extends JFrame's initializer):

addWindowListener(this::exitBtnActionPerformed);

... to call METHOD 2, does not work for when I try to replace this:

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

Instead it gives me this error:

- 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
Wabbage
  • 437
  • 3
  • 6
  • 18

1 Answers1

2

A functional interface is an interface that has only one abstract method.

The method reference does not work for the 2nd method because WindowListener is not a functional interface; unlike the ActionListener interface which has a single abstract method actionPerformed().

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67