JavaFX - Event Handlers



Event handlers enable you to handle an event during the event bubbling phase of event processing.

The bubbling phase of an event route is a phase where the event travels from target node to stage node. Like Event filters, a node can have one or more handlers, or no handlers at all to handle an event. If the node does not contain a handler, the event reaches the root node and the process is completed. Otherwise, if a node in event dispatch chain contains a handler, the handler is executed.

A single handler can be used for more than one node and more than one event type. If an event handler for a child node does not consume the event, an event handler for a parent node enables the parent node to act on the event after a child node processes it and to provide common event processing for multiple child nodes.

Adding and Removing Event Handlers

To add an event handler to a node, you need to register this handler using the method addEventHandler() of the Node class as shown below.

//Creating the mouse event handler 
EventHandler<javafx.scene.input.MouseEvent> eventHandler = 
   new EventHandler<javafx.scene.input.MouseEvent>() { 
   
   @Override 
   public void handle(javafx.scene.input.MouseEvent e) { 
      System.out.println("Hello World"); 
      circle.setFill(Color.DARKSLATEBLUE);             
   } 
};    
//Adding the event handler 
circle.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandler);

In the same way, you can remove an event handler using the method removeEventHandler() as shown below −

circle.removeEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler);

Example

The following program is an example demonstrating the event handling in JavaFX using the event handlers.

Save this code in a file with name EventHandlersExample.java.

import javafx.animation.RotateTransition; 
import javafx.application.Application; 
import javafx.event.EventHandler; 

import javafx.scene.Group; 
import javafx.scene.PerspectiveCamera; 
import javafx.scene.Scene; 
import javafx.scene.control.TextField; 
import javafx.scene.input.KeyEvent; 
import javafx.scene.paint.Color; 
import javafx.scene.paint.PhongMaterial;
 
import javafx.scene.shape.Box; 
import javafx.scene.text.Font; 
import javafx.scene.text.FontWeight; 
import javafx.scene.text.Text;  
import javafx.scene.transform.Rotate; 
import javafx.stage.Stage; 
import javafx.util.Duration; 
         
public class EventHandlersExample extends Application { 
   
   @Override 
   public void start(Stage stage) {
      //Drawing a Box 
      Box box = new Box(); 
      
      //Setting the properties of the Box 
      box.setWidth(150.0); 
      box.setHeight(150.0);   
      box.setDepth(100.0); 
       
      //Setting the position of the box 
      box.setTranslateX(350);  
      box.setTranslateY(150); 
      box.setTranslateZ(50); 
       
      //Setting the text 
      Text text = new Text("Type any letter to rotate the box, 
         and click on the box to stop the rotation"); 
      
      //Setting the font of the text 
      text.setFont(Font.font(null, FontWeight.BOLD, 15));     
      
      //Setting the color of the text 
      text.setFill(Color.CRIMSON); 
      
      //setting the position of the text 
      text.setX(20); 
      text.setY(50); 
       
      //Setting the material of the box 
      PhongMaterial material = new PhongMaterial();  
      material.setDiffuseColor(Color.DARKSLATEBLUE);  
      
      //Setting the diffuse color material to box 
      box.setMaterial(material);       
       
      //Setting the rotation animation to the box    
      RotateTransition rotateTransition = new RotateTransition(); 
      
      //Setting the duration for the transition 
      rotateTransition.setDuration(Duration.millis(1000)); 
      
      //Setting the node for the transition 
      rotateTransition.setNode(box);       
      
      //Setting the axis of the rotation 
      rotateTransition.setAxis(Rotate.Y_AXIS); 
      
      //Setting the angle of the rotation
      rotateTransition.setByAngle(360); 
      
      //Setting the cycle count for the transition 
      rotateTransition.setCycleCount(50); 
      
      //Setting auto reverse value to false 
      rotateTransition.setAutoReverse(false);  
      
      //Creating a text filed 
      TextField textField = new TextField();   
      
      //Setting the position of the text field 
      textField.setLayoutX(50); 
      textField.setLayoutY(100); 
       
      //Handling the key typed event 
      EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() { 
         @Override 
         public void handle(KeyEvent event) { 
            //Playing the animation 
            rotateTransition.play(); 
         }           
      };              
      //Adding an event handler to the text feld 
      textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField); 
       
      //Handling the mouse clicked event(on box) 
      EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox = 
         new EventHandler<javafx.scene.input.MouseEvent>() { 
         
         @Override 
         public void handle(javafx.scene.input.MouseEvent e) { 
            rotateTransition.stop();  
         } 
      }; 
      //Adding the event handler to the box  
      box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandlerBox);
       
      //Creating a Group object
      Group root = new Group(box, textField, text); 
         
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);      
      
      //Setting camera 
      PerspectiveCamera camera = new PerspectiveCamera(false); 
      camera.setTranslateX(0); 
      camera.setTranslateY(0); 
      camera.setTranslateZ(0); 
      scene.setCamera(camera);  
      
      //Setting title to the Stage 
      stage.setTitle("Event Handlers Example"); 
         
      //Adding scene to the stage 
      stage.setScene(scene); 
         
      //Displaying the contents of the stage 
      stage.show(); 
   } 
   public static void main(String args[]){ 
      launch(args); 
   } 
}

Compile and execute the saved java file from the command prompt using the following commands.

javac --module-path %PATH_TO_FX% --add-modules javafx.controls EventHandlersExample.java 
java --module-path %PATH_TO_FX% --add-modules javafx.controls EventHandlersExample

Output

On executing, the above program generates a JavaFX window displaying a text field and a 3D box as shown below −

Text Field

Here, if you type a letter in the text field, the 3D box starts rotating along the x axis. If you click on the box again the rotation stops.

Example

Let us see another scenario where we can use Event Handlers. In this example, we are creating a JavaFX object, say a circle, and applying Fade Transition on it. Using an event handler, we are specifying when the Transition needs to be played and when to be paused; i.e. by clicking on a button.

Save this code in a file with name EventHandlersButton.java.

import javafx.animation.ScaleTransition;  
import javafx.application.Application;  
import javafx.event.EventHandler;  
import javafx.scene.Group;  
import javafx.scene.Scene;  
import javafx.scene.control.Button;  
import javafx.scene.input.MouseEvent;  
import javafx.scene.paint.Color;  
import javafx.scene.shape.Circle;  
import javafx.stage.Stage;  
import javafx.util.Duration;

public class EventHandlerButton extends Application{  
@Override  
   public void start(Stage primaryStage) throws Exception {  
      // TODO Auto-generated method stub  
      //Creating Circle and setting the color and stroke in the circle   
      Circle c = new Circle(150, 125, 50);  
      c.setFill(Color.RED);  
      c.setStroke(Color.BLACK);  
      
      //creating play button and setting coordinates for the button   
      Button btn = new Button("Play");  
      btn.setTranslateX(100);  
      btn.setTranslateY(250);  
      
      // creating pause button and setting coordinate for the pause button   
      Button btn1 = new Button("Pause");  
      btn1.setTranslateX(150);  
      btn1.setTranslateY(250);  
      
      //Instantiating TranslateTransition class to create the animation   
      ScaleTransition st = new ScaleTransition();  
      
      //setting attributes for the TranslateTransition
      st.setNode(c); 
      st.setDuration(Duration.millis(1000)); 
      st.setByX(1);
      st.setByY(1); 	  
      st.setAutoReverse(true);  
  
      st.setCycleCount(50);
      
      //Creating EventHandler   
      EventHandler<MouseEvent> handler = new EventHandler() {  
         @Override  
         public void handle(MouseEvent event) {  
            // TODO Auto-generated method stub  
            if(event.getSource()==btn) {  
               st.play(); //animation will be played when the play button is clicked   
            }  
            if(event.getSource()==btn1) {  
               st.pause(); //animation will be paused when the pause button is clicked   
            }  
            event.consume();  
         }  
          
      };  
      
      //Adding Handler for the play and pause button   
      btn.setOnMouseClicked(handler);  
      btn1.setOnMouseClicked(handler);  
      
      // Creating Group Object   
      Group root = new Group();
      root.getChildren().addAll(c, btn, btn1);

      // Creating Scene Object	  
      Scene scene = new Scene(root, 300, 300);
      primaryStage.setScene(scene);
	  
	  // Adding Title to Application
      primaryStage.setTitle("EventHandler Button");  
      primaryStage.show();  
   }  
   public static void main(String[] args) {  
      launch(args);  
   }  
}  

Compile and execute the saved java file from the command prompt using the following commands.

javac --module-path %PATH_TO_FX% --add-modules javafx.controls EventHandlersButton.java 
java --module-path %PATH_TO_FX% --add-modules javafx.controls EventHandlersButton

Output

On executing, the above program generates a JavaFX window displaying a circle with fade transition.

Text Field
Advertisements