JavaFX Event Handlers

Introduction to Event Handlers in JavaFX

Event handlers in JavaFX are used to listen for and handle events that occur in a scene. Events can be generated by the user interacting with the UI, such as clicking a button or pressing a key, or by the system, such as a window being resized or a file being dropped.

To handle an event, you must first register an event handler for the event. Event handlers can be registered for individual nodes or for the entire scene. To register an event handler for a node, you use the `addEventHandler()` method. To register an event handler for the scene, you use the `addEventFilter()` method.

Event handlers are typically implemented as lambda expressions. Lambda expressions are a concise way to write functions. For example, the following lambda expression registers an event handler for the `onClick()` event of a button:


button.setOnAction(event -> {
// Handle the button click event
});

When the user clicks the button, the lambda expression will be executed.

JavaFX provides a variety of built-in event handlers for common events, such as onClick(), onKeyPressed(), and onMouseMoved(). You can also create your own custom event handlers.

Here is an example of a simple application that uses event handlers:


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;

public class MyApp extends Application {

@Override
public void start(Stage stage) throws Exception {
Button button = new Button("Click Me!");

button.setOnAction(event -> {
  System.out.println("You clicked the button!");
});

Scene scene = new Scene(button);

stage.setTitle("My JavaFX Application");
stage.setScene(scene);
stage.show();

}

public static void main(String[] args) {
launch(args);
}
}

When you run this application and click the button, the message "You clicked the button!" will be printed to the console.

Event handlers are a powerful tool for creating interactive JavaFX applications. By understanding how to use event handlers, you can create applications that respond to user input and system events in a variety of ways.

Exercises

Code for getting input from a text field in javafx


import java.io.*;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class democlass extends Application{
  
    public static void main(String[] args){
  
    launch(args);
    }

  @Override
  public void start(Stage primaryStage) throws Exception {
  
    //this is a demo for creating a textfield and password field in javafx
    TextField name = new TextField();
    name.setMaxWidth(300);
    PasswordField pass = new PasswordField();
    pass.setMaxWidth(300);
    Button bt1 = new Button("Click here");
    Label lbl = new Label();
    bt1.setOnAction(new EventHandler<ActionEvent>() {
      
      @Override
      public void handle(ActionEvent event) {
        lbl.setText("Welcome Mr. " +name.getText());
        lbl.setTextFill(Color.RED);
        lbl.setFont(new Font(32));
        
      }
    });
    
    VBox root = new VBox();
    root.getChildren().addAll(name,pass,bt1,lbl);
    //add this layout to a scene
    Scene sc = new Scene(root);
    //set scene with primary stage
    primaryStage.setTitle("Javafx UI Control Demo");
    primaryStage.setScene(sc);
    primaryStage.setWidth(500);
    primaryStage.setHeight(500);
    primaryStage.show();
  }
} 

Code for reading input from a radio button in javafx


package practiceproject;
import java.io.*;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class democlass extends Application{
  
    public static void main(String[] args){
  
    launch(args);
    }

  @Override
  public void start(Stage primaryStage) throws Exception {
  
    //reading input from radio button in JavaFX 
    ToggleGroup group = new ToggleGroup();
    RadioButton opt1 = new RadioButton("English");
    RadioButton opt2 = new RadioButton("Physics");
    RadioButton opt3 = new RadioButton("Maths");
    RadioButton opt4 = new RadioButton("Computer Science");
    Button submit = new Button("Submit");
    Label lb1 = new Label();
    opt1.setToggleGroup(group);
    opt2.setToggleGroup(group);
    opt3.setToggleGroup(group);
    opt4.setToggleGroup(group);
      VBox root = new VBox();
    root.getChildren().addAll(opt1,opt2,opt3,opt4,submit,lb1);
    submit.setOnAction(new EventHandler<ActionEvent>() {
      
      @Override
      public void handle(ActionEvent event) {
        // TODO Auto-generated method stub
        if(opt1.isSelected())
        {
          lb1.setText("you have selected".concat(opt1.getText()));
        }
        else
        {
          lb1.setText("You have selected Wrong Answer");
        }

      }
    });
    //add this layout to a scene
    Scene sc = new Scene(root);
    //set scene with primary stage
    primaryStage.setTitle("Javafx UI Control Demo");
    primaryStage.setScene(sc);
    primaryStage.setWidth(500);
    primaryStage.setHeight(500);
    primaryStage.show();
  }
} 

Code for getting input from a checkbox in javafx


package practiceproject;
import java.io.*;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class democlass extends Application{
  
    public static void main(String[] args){
  
    launch(args);
    }

  @Override
  public void start(Stage primaryStage) throws Exception {
  
    //reading input from a check box in JavaFX 
    //Creating a checkbox
    CheckBox opt1 = new CheckBox("English");
    CheckBox opt2 = new CheckBox("Physics");
    CheckBox opt3 = new CheckBox("DBMS");
    CheckBox opt4 = new CheckBox("Computer Science");
    //adding a submit button 
    Button submit = new Button("Submit");
    //adding a label for output 
    Label lbl = new Label();
    VBox root = new VBox();
    
    root.getChildren().addAll(opt1,opt2,opt3,opt4,submit,lbl);
    submit.setOnAction(new EventHandler<ActionEvent>() {
      String selectedoptions="";
      @Override
      public void handle(ActionEvent event) {
        // TODO Auto-generated method stub
        
        if(opt1.isSelected())
          {
              selectedoptions+=opt1.getText();
              selectedoptions+=" ";
          }
          if(opt2.isSelected())
          {
            selectedoptions+=opt2.getText();
            selectedoptions+=" ";
          }
          if(opt3.isSelected())
          {
            selectedoptions+=opt3.getText();
            selectedoptions+=" ";
          }
          if(opt4.isSelected())
          {
            selectedoptions+=opt4.getText();
          
          }
        
          if(selectedoptions.isEmpty())
          {
            lbl.setText("Select some Check box Options");
          }
          else
          {
            lbl.setText("The subjects you have selected are "+ selectedoptions);
          }
        
      }
    });
    //add this layout to a scene
    Scene sc = new Scene(root);
    //set scene with primary stage
    primaryStage.setTitle("Javafx UI Control Demo");
    primaryStage.setScene(sc);
    primaryStage.setWidth(500);
    primaryStage.setHeight(500);
    primaryStage.show();
  }
} 

Code for getting input from a combobox in javafx


package practiceproject;
import java.io.*;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class democlass extends Application{
  
    public static void main(String[] args){
  
    launch(args);
    }

  @Override
  public void start(Stage primaryStage) throws Exception {
  
    //creating a combo box 
    ComboBox subjects = new ComboBox();
    subjects.getItems().add("English");
    subjects.getItems().add("Maths");
    subjects.getItems().add("Physics");
    subjects.getItems().add("Chemistry");
    //adding a submit button 
    Button submit = new Button("Submit");
    //adding a label for output 
    Label lbl = new Label();
    VBox root = new VBox();
    root.getChildren().addAll(subjects,submit,lbl);
    submit.setOnAction(new EventHandler() {
      
      @Override
      public void handle(ActionEvent event) {
        // TODO Auto-generated method stub
        
        if(subjects.getValue()==null)
        {
          lbl.setText("Please select an Option");
        }
        else
        {
          lbl.setText("you have selected "+subjects.getValue());
        }
        
      }
    });
    //add this layout to a scene
    Scene sc = new Scene(root);
    //set scene with primary stage
    primaryStage.setTitle("Javafx UI Control Demo");
    primaryStage.setScene(sc);
    primaryStage.setWidth(500);
    primaryStage.setHeight(500);
    primaryStage.show();
  }
}