How to capture an event to force close or unexpected close in JavaFx?

I am creating a desktop application that has a login and logout with a server.

I need to exit the application when someone closes the window, so I use these codes

primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { event.consume(); closeWindow(); } }); 

where closeWindow () contains the logout and other related steps.

Now there is a problem when the application unexpectedly closes or when someone forcibly terminates / closes it from the task manager (by completing the process).

Is there any event in JavaFX for forced closure or unexpected closure? Or if there is a way to stop him?

+6
source share
4 answers

When your application closes using the TaskManager , the only option would be to use the VM shutdown hook .

There are several examples, for example, here .

+4
source

There is a method

 @Override public void stop() throws Exception { super.stop(); System.out.println("logout"); } 

in the class Application.

+3
source
 public class Gui extends Application { static { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { closeWindow(); } }); } @Override public final void start(Stage primaryStage) throws Exception { // ... } @Override public void stop() throws Exception { // ... System.exit(0); } } 
+1
source

If you use a task for this exit procedure, try playing with the setDaemon method. I solved a similar case by showing the download window and closing this window after completing the task. You can also try this.

0
source

All Articles