Shreyas Dave
Shreyas Dave

Reputation: 3855

How to capture event for forcefully quit or unexpected close in JavaFx?

I am making a desktop application which has login and logout functionality with server.

I need to logout from the application whenever someone close the window, so I am using these codes

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

where closeWindow() contains logout and other related steps.

Now there is a problem when application closes unexpectedly or when someone forcefully quit/close it from Task Manager (by ending process).

Do JavaFX has any event to capture forcefully quit or unexpected close ? Or if there any method to stop it ?

Upvotes: 6

Views: 3775

Answers (4)

user2636594
user2636594

Reputation:

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);
    }
}

Upvotes: 2

Ramazan
Ramazan

Reputation: 999

If you are using a task for that logout procedure, try playing with setDaemon method. I solved a similar case by showing a "loading" window and closing that window after the task completes. You can try that too.

Upvotes: 0

Alexander Kirov
Alexander Kirov

Reputation: 3654

There is a method

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

in Application class.

Upvotes: 3

flash
flash

Reputation: 6820

When your application gets closed via TaskManager your only option will be to use the VM's shutdown hook.

There are some examples around, e.g. here.

Upvotes: 4

Related Questions