javajavafxshutdown-hook

what event is fired when you close a javafx application from the task bar and how do you handle it?


I've seen a few posts about this that have answers marked as correct even though they don't seem to work for which could be for a number of reasons.

Example

What I would like is to handle the event in which the user closes the application from the taskbar by right-clicking on the application, I would like to handle this to ensure a clean shutdown and to make sure all user data is saved.

I have tried adding a shutdown hook (example below) but that wasn't triggered when closing the application from the taskbar

Runtime.getRuntime().addShutdownHook(new Thread(()->{
    System.out.println("closing . . .");
}));

The other method I tried was to add a setOnCloseRequest listener for my stage as shown below but the WINDOW_CLOSE_REQUEST event also wasn't fired when closing the application form the taskbar.

stage.setOnCloseRequest(event2 -> {
   System.out.println("closing . . .");
   Platform.exit();
   System.exit(0);
});

Solution

  • Based on @James_D's response I realized I was adding the shutdown hook in the incorrect place, to help anyone else who is relatively new to java and JavaFX when adding a shutdown hook you must do it before calling launch(args) in the main method.