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


Question

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)");
       //}
   }
1
13
10/7/2017 2:09:12 AM

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);
                 }
             });
         }
     });
15
10/7/2017 5:51:20 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon