使用方法引用

编程入门 行业动态 更新时间:2024-10-22 11:25:06
本文介绍了使用方法引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个名为 saveButton 的 JButton ,并希望它调用保存单击时的方法。当然我们可以使用旧方法来做到这一点:

I've got a JButtoncalled saveButton and want it to call the save method when it is clicked. Of course we can do it using the old approach:

saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { save(); } });

但今天我想使用方法引用等新的Java 8功能。为什么

But today I want to use new Java 8 features like method references. Why does

saveButton.addActionListener(this::save);

不起作用?如何使用方法引用完成?

not work? How is it done using method references?

推荐答案

方法 actionPerformed(ActionEvent e)需要单个参数 e 。如果要使用方法引用,则方法必须具有相同的签名。

Method actionPerformed(ActionEvent e) requires single parameter e. If you want to use a method reference, your method must have the same signature.

private void myActionPerformed(ActionEvent e) { save(); }

然后你可以使用方法参考:

Then you can use method reference:

saveButton.addActionListener(this::myActionPerformed);

或者你可以改用lambda(注意 e 参数):

Or you can use lambda instead (notice e parameter):

saveButton.addActionListener(e -> save());

更多推荐

使用方法引用

本文发布于:2023-10-11 22:47:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483056.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:使用方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!