JavaFX Button click event
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:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics