gpt4 book ai didi

java - 方法引用未按预期工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:16:12 26 4
gpt4 key购买 nike

<分区>

我的 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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com