您可以使用 lambda:
saveButton.addActionListener((ActionEvent e) -> save());
可以这样做是因为 ActionListener 是一个功能接口(即只有一个方法)。功能接口是任何只包含一个抽象方法的接口。Lambda 是调用的简写。
除了使用 Lambda,您还可以通过让您的类实现相关接口(或其他具有实例变量的类)来使用方法引用。这是一个完整的例子:
public class Scratch implements ActionListener {
static JButton saveButton = new JButton();
public void save(){};
public void contrivedExampleMethod() {
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
save();
}
});
// This works regarless of whether or not this class
// implements ActionListener, LAMBDA VERSION
saveButton.addActionListener((ActionEvent e) -> save());
// For this to work we must ensure they match
// hence this can be done, METHOD REFERENCE VERSION
saveButton.addActionListener(this::actionPerformed);
}
@Override
public void actionPerformed(ActionEvent e) {
save();
}
}
这当然只是一个人为的例子,但它可以通过任何一种方式完成,假设您传递了正确的方法或使用 Lambdas 创建正确的内部类(类似)实现。由于动态特性,我认为 lambda 方式在实现您想要的方面更有效。毕竟这就是他们在那里的原因。