How do I get the close event of a stage in JavaFX?
Asked Answered
P

3

17

In JavaFX, how can I get the event if a user clicks the Close Button(X) (right most top cross) a stage?

I want my application to print a debug message when the window is closed. (System.out.println("Application Close by click to Close Button(X)"))

@Override
   public void start(Stage primaryStage) {
        StackPane root = new StackPane();
       root.getChildren().add(btn);
       Scene scene = new Scene(root, 300, 250);
       primaryStage.setTitle("Hello World!");
       primaryStage.setScene(scene);
       primaryStage.show();

       // Any Event Handler
       //{
       System.out.println("Application(primaryStage) Closed by click to Close Button(X)");
       //}
   }
Prate answered 22/3, 2014 at 10:15 Comment(0)
P
18

I got the answer for this question

stage.setOnHiding(new EventHandler<WindowEvent>() {

         @Override
         public void handle(WindowEvent event) {
             Platform.runLater(new Runnable() {

                 @Override
                 public void run() {
                     System.out.println("Application Closed by click to Close Button(X)");
                     System.exit(0);
                 }
             });
         }
     });
Prate answered 22/3, 2014 at 10:54 Comment(4)
It"s stage.setOnCloseRequest(...).Departed
.setOnHiding worked for me and .setOnCloseRequest did notGoods
Are there any way to close window without System.exit call?Ronel
setOnCloseRequest will only be called when there's external request to close the window, I assume this means manually clicking close button. This also means it won't be triggered by stage.close() calls.Threlkeld
E
13

Another method for achieving the same effect, but remains more consistent with the way you start your application is to override stop();

According to the JavaFX documentation, the lifecycle of an instance of an Application is as follows:

The JavaFX runtime does the following, in order, whenever an application is launched:

  1. Constructs an instance of the specified Application class
  2. Calls the init() method
  3. Calls the start(javafx.stage.Stage) method
  4. Waits for the application to finish, which happens when either of the following occur:
    • the application calls Platform.exit()
    • the last window has been closed and the implicitExit attribute on Platform is true
  5. Calls the stop() method

As a result you simply override stop()

@Override
public void stop(){
    System.out.println("Stage is closing");
}
Epexegesis answered 16/2, 2016 at 4:19 Comment(0)
S
8
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
      public void handle(WindowEvent we) {
          System.out.println("Stage is closing");
      }
  }); 
Selfridge answered 16/2, 2016 at 5:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.