How to write lambda expression with EventHandler javafx
13,908
The lambda expression is here to replace the whole FunctionalInterface
and not only its method, so it's not constructor + lambda
but only lambda
:
Use the
EventHandler
as parameter :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<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 :
Runnable r = () -> System.out.println("Here");
Related videos on Youtube
Author by
Pascal Hoffenheimer
Updated on June 04, 2022Comments
-
Pascal Hoffenheimer almost 2 years
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?
-
James_D over 6 yearsThe lambda equivalent of the first code block is just
event -> System.out.println(event.hashCode())
(without the call to a constructor, which is I think what you are trying to do). -
Dota2 over 6 yearsin simple words it is the entire
functional interface
that you replace with lambda and not the function within the interface. The lambda equivalent of ur first code snippet isevent -> System.out.println(e.hashCode())
. What you are doing is basically adding "lambda" in constructor. Invalid -
azro about 6 years@Pascal Hoffenheimer if the answer satisfies you, you may accept it, it's how a forum works, if you didn't, people with same problem won't come see the solution because the post would appear as "unsolved"
-
Pascal Hoffenheimer over 4 yearsI understand my mistakes: 1. Constructor is to be left out. 2. Use parameter name. Don't rename it.
-
-
Mahendran about 6 yearsAssume am not going to use the event parameter at all, Any way I can just drop it or any special variable name (_) like in Kotlin?
-
azro about 6 years@mahemadhi not in this case, because the method of
EventHandler
does have a parameter, but for a Supplier/Runnable/... you can (see edit) -
Mahendran about 6 yearsAm sorry to confuse you.. It's just another question