Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 552
Pascal Hoffenheimer Avatar asked Aug 01 '26 22:08

Pascal Hoffenheimer


1 Answers

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");
like image 57
azro Avatar answered Aug 03 '26 11:08

azro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!