Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

javafx-2

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 ?

like image 641
Shreyas Dave Avatar asked Feb 25 '13 11:02

Shreyas Dave


3 Answers

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.

like image 125
flash Avatar answered Oct 31 '22 20:10

flash


There is a method

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

in Application class.

like image 20
Alexander Kirov Avatar answered Oct 31 '22 21:10

Alexander Kirov


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);
    }
}
like image 35
Dima G. Avatar answered Oct 31 '22 21:10

Dima G.