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

后端 未结 3 1502
有刺的猬
有刺的猬 2021-02-19 03:09

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

相关标签:
3条回答
  • 2021-02-19 03:53

    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);
                     }
                 });
             }
         });
    
    0 讨论(0)
  • 2021-02-19 04:02

    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");
    }
    
    0 讨论(0)
  • 2021-02-19 04:11
    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
          public void handle(WindowEvent we) {
              System.out.println("Stage is closing");
          }
      }); 
    
    0 讨论(0)
提交回复
热议问题