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:


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 {

    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() {
            public void handle(ActionEvent event) {
                // Display a message when the button is clicked
                System.out.println("Button Clicked!");

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


    public static void main(String[] 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: 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.