In this tutorial, we will learn how to stop or terminate the JavaFX application.
JavaFX Quit Button Example - Terminate Application
In the following example, we have a Button control. When we click on the button, the application terminates. When a button is pressed and released, an ActionEvent is sent.
package com.javaguides.javafx;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class QuitButtonExample extends Application {
@Override
public void start(Stage stage) {
Button btn = new Button();
btn.setText("Quit");
btn.setOnAction((ActionEvent event) -> {
Platform.exit();
});
HBox root = new HBox();
root.setPadding(new Insets(25));
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 220);
stage.setTitle("Quit button");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Let's understand the above JavaFX program.
Note that Button control is placed in the upper-left corner of the window. An event handler is added to the button.
A Button control is instantiated. The setText() methods sets the button's label:
Button btn = new Button();
btn.setText("Quit");
The setOnAction() method sets the button's action, which is invoked whenever the button is fired. The above code creates an anonymous event handler. The Platform.exit() terminates the application:
btn.setOnAction((ActionEvent event) -> {
Platform.exit();
});
HBox is a pane that lays out its children in a single horizontal row. The setPadding() method creates a padding around the content of the pane. (The default padding is Insets.EMPTY.) This way there is some space between the button and the edges of the window borders:
HBox root = new HBox();
root.setPadding(new Insets(25));
The button is added to the HBox pane:
root.getChildren().add(btn);
Output
Related JavaFX Examples
- JavaFX Hello World Example Tutorial - In this tutorial, we will learn how to create our first JavaFX application.
- Registration Form Using JavaFX with MySQL Database - In this tutorial, we will learn how to create a Registration Form using JavaFX with database connectivity. Here we will use the MySQL database to store user data via JDBC API.
- Login Form Using JavaFX with MySQL Database - In this tutorial, we will learn how to create a Login Form using JavaFX with database connectivity.
Comments
Post a Comment
Leave Comment