JavaFX close application
When you are closing your JavaFX application don’t call the System.exit() method as you may be used to doing in other Java programs. I think many beginners wonder how to properly close a JavaFX application. Unlike the Java Swing, we can just simply close the application by calling the System.exit() method.
In this tutorial, I will show you some examples of closing the entire JavaFX application and a specific window.
How to close a JavaFX application or window
Close a JavaFX application or window by calling the Platform.exit() method to properly close a JavaFX application or window. By performing this method, your entire JavaFX application will close. This means that all of your stages will be closed too. Simply call the javafx.application.Platform.exit() to define it properly on your code.
Example 1: This will close your JavaFX application entirely
In this example, I used the MouseEvent to perform an action in the close button using an undecorated stage.
@FXML private void Close_clicked(MouseEvent event) { javafx.application.Platform.exit(); }
Example 2: Closing the application in the decorated window
In this example, I defined the stage.setOnCloseRequest() and used the Lambda function to perform the close button on the decorated stage.
stage.setOnCloseRequest(event ->{ javafx.application.Platform.exit(); });
How to close a window in the JavaFX application
If you have multiple stages or windows opened in your JavaFX application and you want to close one of them. Then to close it properly, you may need to call the close() method. The close() is equivalent to hide. To define it properly in your code. See the example code below.
Example 1: If you are using a decorated stage
In this example, I am closing the window using the decorated window, and I used a Lambda function to close the window.
stage.setOnCloseRequest(event ->{ stage.close(); });