How to implement JavaFX event handling using lambda in Java?

Java 8Object Oriented ProgrammingProgramming

JavaFX Button class provides the setOnAction() method that can be used to set an action for the button click event. An EventHandler is a functional interface and holds only one method is the handle() method.

Syntax

@FunctionalInterface
public interface EventHandler<T extends Event> extends EventListener

In the below example, we can able to implement event handling of JavaFX by using a lambda expression.

Example

import javafx.application.*;
import javafx.beans.property.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;

public class LambdaWithJavaFxTest extends Application {
   public static void main(String[] args) {
      Application.launch(args);
   }
   @Override
   public void start(Stage stage) throws Exception {
      BorderPane root = new BorderPane();
      ToggleButton button = new ToggleButton("Click");

      final StringProperty btnText = button.textProperty();
      button.setOnAction((event) -> {    // lambda expression
         ToggleButton source = (ToggleButton) event.getSource();
         if(source.isSelected()) {
            btnText.set("Clicked!");
         } else {
            btnText.set("Click!");
         }
      });
      root.setCenter(button);  
      Scene scene = new Scene(root);
      stage.setScene(scene);
      stage.setWidth(300);
      stage.setHeight(250);
      stage.show();
   }
}

Output





raja
Published on 08-Jan-2020 12:49:32
Advertisements