Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Tracy Bowers
10,136 PointsEvent handler explanation. Too advanced to fast?
Craig/all, jumping to passing Lambdas to the even handler lost me. Perhaps I would have benefited in learning the old way first. Event handlers and life before Lambdas. After all Lambdas are relatively new to Java,
How would one use an event handler without a Lambda? Lambdas are relatively new to Java I think. How did our forefathers implement event handlers. :-)
1 Answer
Mihai Craciun
13,520 PointsLet's take a simple example, adding an event handler to a button:
This is how it should look like without lambda
playButton.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
System.out.println("Playing!");
}
});
And this is how it should look like with lambda
playButton.setOnAction(event -> System.out.println("Playing!"));
As you can see lambdas are much more concise and not that hard to understand as long as you know what to point
Tracy Bowers
10,136 PointsTracy Bowers
10,136 PointsThanks for the response. Wrapping my head around passing whole functions as parameters. Brain just went POOF!
What I think is happening here is this: The event handler needs to do something when the event is triggered. That something needs to be packaged into a function and a reference to that function needs to be registered with the event handler.
Agreed that the Lambda was a good thing; however, what if your function needs to be more complex? Does it make sense jamming it all in as a parameter? Can the function exist as a regular function and that regular function be passed as a parameter?
Mihai Craciun
13,520 PointsMihai Craciun
13,520 PointsWell if the function is more complex you only need to add parentheses like this
but if you really want to pass it as a parameter nobody stops you