JavaFX Button click event
5. Button Click Console Message
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:
Flowchart:

Go to:
PREV : Change Background with Key Combination.
NEXT : Simple Calculator with Button Events.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
