How to implement ActionEvent using method reference in JavaFX?


The javafx.event package provides a framework for Java FX events. The Event class serves as the base class for JavaFX events and associated with each event is an event source, an event target, and an event type. An ActionEvent widely used when a button is pressed.

In the below program, we can implement an ActionEvent for a button by using method reference.

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.*;
import javafx.scene.effect.*;

public class MethodReferenceJavaFXTest extends Application {
   private Label label;
   public static void main(String[] args) {
      launch(args);
   }
   @Override
   public void start(Stage primaryStage) {
      Pane root = new StackPane();
      label = new Label("Method Reference");
      Button clickMe = new Button("Click Me");
      clickMe.setOnAction(this::handleClickMe);    // method reference
      root.getChildren().addAll(label, clickMe);

      primaryStage.setTitle("Method Reference Test");
      primaryStage.setScene(new Scene(root, 300, 200));
      primaryStage.show();
   }
   private void handleClickMe(ActionEvent event) {
      if(label.getEffect() == null) {
         label.setEffect(new BoxBlur());
      } else {
         label.setEffect(null);
      }
   }
}

Output



Updated on: 13-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements