java – How to capture the closing event on a Stage?

Question:

I'm looking for an event like the "windows close" of Swing.

Answer:

You can call your Stage's setOnCloseRequest method, so you can perform an action as soon as the user clicks the button to close the window.

Ex.:

public class Teste extends Application {
    @Override
    public void start(Stage stage) {
        stage.setOnCloseRequest(event -> System.out.println("Fechando o programa"));

        Parent root = FXMLLoader.load(getClass().getResource("main.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Scroll to Top