How to write lambda expression with EventHandler javafx

Pascal Hoffenheimer picture Pascal Hoffenheimer · Jul 25, 2017 · Viewed 11k times · Source

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?

Answer

azro picture azro · Jul 25, 2017

The lambda expression is here to replace the whole FunctionalInterface and not only its method, so it's not constructor + lambda but only lambda :

  1. 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()));
    

  1. 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");