2

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);
});
  • Have you tried onClick – David Enoma May 02 '20 at 10:48
  • @DavidEnoma could you give an example of how I could add an onClick listener to a taskbar option please –  May 02 '20 at 10:59
  • I booted up a Windows 10 VM in Virtual Box and ran this [example](https://stackoverflow.com/a/42598179/2189127). Choosing "Close Window" from the task bar invoked both the `Application.stop()` method and the shutdown hook. If I hang the program, however, and force it to close from the task bar, neither are invoked. (The behavior is the same from Task Manager in both cases.) Since you probably can't do anything anyway if you've allowed your application to hang, that seems to be the best you could hope for. If it works differently for you, post a reproducible example in your question. – James_D May 02 '20 at 13:16

1 Answers1

0

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.

  • Ah, yes, I remember something like that. I'll update the answer to the other question, and then mark this as a duplicate: that's probably the most useful for other users. – James_D May 02 '20 at 14:06