[英]How to write lambda expression with EventHandler javafx
I'm trying to rewrite this code我正在尝试重写此代码
new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
System.out.println(e.hashCode());
}
};
as作为
new EventHandler<MouseEvent>(e -> System.out.println(e.hashCode()));
and I get errors.我得到错误。 What is my mistake here?我在这里有什么错误?
The lambda expression is here to replace the whole FunctionalInterface
and not only its method, so it's not constructor + lambda
but only lambda
: lambda 表达式在这里替换整个FunctionalInterface
而不仅仅是它的方法,所以它不是constructor + lambda
而只是lambda
:
Use the EventHandler
as parameter :使用EventHandler
作为参数:
someNode.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { System.out.println(event.hashCode()); } });
Becomes :变成:
someNode.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> System.out.println(event.hashCode()));
Use the EventHandler
in a variable :在变量中使用EventHandler
:
EventHandler<MouseEvent> eh = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { System.out.println(event.hashCode()); } };
It'll become :它会变成:
EventHandler<MouseEvent> eh = e -> System.out.println(e.hashCode());
It's exists various way to use lambda, with or without parameter, like :它存在多种使用 lambda 的方式,带或不带参数,例如:
Runnable r = () -> System.out.println("Here");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.