Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFx Controller: detect when stage is closing

Tags:

java

javafx-8

I have a javaFx project and I would like to implement a method inside the Controller that is invoked every time the stage(window) is closing this to be able to perform some actions before closing it. The desire to have the method placed inside the controller is because the actions to be taken depend on the choices that the user has made while using the scene.

My goal is every time the user closes the stage, to have a print and then an user related action.

I try inside the controller class:

@FXML
    public void exitApplication(ActionEvent event) {
        System.out.println("stop");
        action();
        Platform.exit();
    }

but it's no effective.

like image 911
Francesco Avatar asked Jun 08 '17 15:06

Francesco


1 Answers

Just from a design perspective, it doesn't really make sense in the controller to associate a handler with the stage, as the stage is typically not part of the view to which the controller is connected.

A more natural approach is to define a method in the controller, and then invoke that method from a handler which you associate with the stage at the point where the stage is created.

So you would do something like this in the controller:

public class Controller {

    // fields and event handler methods...


    public void shutdown() {
        // cleanup code here...
        System.out.println("Stop");
        action();
        // note that typically (i.e. if Platform.isImplicitExit() is true, which is the default)
        // closing the last open window will invoke Platform.exit() anyway
        Platform.exit();
    }
}

and then at the point where you load the FXML you would do

FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/file.fxml"));
Parent root = loader.load();
Controller controller = loader.getController();
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.setOnHidden(e -> controller.shutdown());
stage.show();

Again, exiting the application is probably not (or probably should not be) the responsibility of the controller (it's the responsibility of the class that creates the window or manages application life-cycle), so if you really needed to force an exit when the window closed, you would probably move that to the onHidden handler:

public class Controller {

    // fields and event handler methods...


    public void shutdown() {
        // cleanup code here...
        System.out.println("Stop");
        action();
    }
}

and

FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/file.fxml"));
Parent root = loader.load();
Controller controller = loader.getController();
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.setOnHidden(e -> {
    controller.shutdown();
    Platform.exit();
});
stage.show();
like image 129
James_D Avatar answered Nov 08 '22 05:11

James_D