JavaFX: Using a Click Event Handler

This entry is part 25 of 55 in the series JavaFX

For our previous example, we can pass a click button event handler into the function and from the event handler, we will be able to get all sort of information about the event.

Consider the example below.  Once we have the event handler in the handle function in line 52, we can use e.getSource() to test the instance of the button that triggered the event.

Here we have 2 instances of a button class and with an if else statement, we can find out which instance of the button has triggered the call.

Click Event Handler
package javafxapplication20;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;

public class JavaFXApplication20 extends Application {

    Button movButton = new Button("Movie");

    Button gameButton = new Button("Game");

    Label lb = new Label("Which Do You Prefer?");

    public void start(Stage stage) {

        ClickHandler ch = new ClickHandler();

        BorderPane border = new BorderPane();

        border.setPrefSize(300, 250);

        HBox hbox = addHorizontalBox();

        Scene scene = new Scene(border);
        stage.setTitle("Which Button");;
    private class ClickHandler
            implements EventHandler<ActionEvent> {

        public void handle(ActionEvent e) {
            if (e.getSource() == movButton) {
                lb.setText("Movie Button Is Clicked");
            } else {
                if (e.getSource() == gameButton) {
                    lb.setText("Game is Chosen");

    private HBox addHorizontalBox() {

        HBox hbox = new HBox();
        hbox.setPadding(new Insets(15, 12, 15, 12));
        hbox.setSpacing(10);   // Gap between nodes

        hbox.getChildren().addAll(movButton, gameButton);

        return hbox;

    private VBox addVBox() {

        VBox vbox = new VBox();
        vbox.setPadding(new Insets(50)); // Set all sides to 10

        lb.setFont(Font.font("Consolas", FontWeight.BOLD, 24));

        return vbox;

    public static void main(String[] args) {




Series Navigation<< JavaFX: Which Button Is Clicked
JavaFX: Hbox with priority always >>

Leave a comment

Leave a Reply