w3resource

JavaFX Button click event

JavaFx Events and Event Handling: Exercise-5 with Solution

Write a JavaFX form with a button. Implement an event listener to display a message to the console when the button is clicked.

Sample Solution:

JavaFx Code:

//Main.java

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Button Click Event Example");

        // Create a button
        Button button = new Button("Click Me");

        // Add an event handler to the button
        button.setOnAction(new EventHandler() {
            @Override
            public void handle(ActionEvent event) {
                // Display a message when the button is clicked
                System.out.println("Button Clicked!");
            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(button);
        primaryStage.setScene(new Scene(root, 300, 250));

        primaryStage.show();
    }

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

The above code creates a simple JavaFX application with a button. When we click the button, it prints "Button Clicked!" to the console.

Sample Output:

JavaFx: JavaFX Button click event.
JavaFx: JavaFX Button click event.

Flowchart:

Flowchart: JavaFX Button click event.

Java Code Editor:

Previous: JavaFX Key combination color change.
Next: JavaFX simple calculator.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.