JavaFx Controller:检测阶段何时关闭

Fra*_*sco 4 java javafx-8

我有一个javaFx项目,我想在Controller内部实现一个方法,每次阶段(窗口)关闭时调用它,以便能够在关闭它之前执行某些操作.将方法放置在控制器内的愿望是因为要采取的动作取决于用户在使用场景时做出的选择.

我的目标是每次用户关闭舞台,进行打印,然后进行与用户相关的操作.

我在控制器类中尝试:

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

但它没有效果.

Jam*_*s_D 10

仅从设计角度来看,在控制器中将处理程序与阶段关联起来并不合理,因为阶段通常不是控制器所连接的视图的一部分.

更自然的方法是在控制器中定义一个方法,然后从处理程序调用该方法,该处理程序与创建阶段的阶段关联.

所以你会在控制器中做这样的事情:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你加载FXML的那一刻你会做

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();
Run Code Online (Sandbox Code Playgroud)

同样,退出应用程序可能不是(或可能不应该)控制器的责任(它是创建窗口或管理应用程序生命周期的类的责任),所以如果你真的需要强制退出时窗口关闭,您可能会将其移动到onHidden处理程序:

public class Controller {

    // fields and event handler methods...


    public void shutdown() {
        // cleanup code here...
        System.out.println("Stop");
        action();
    }
}
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

  • 你可能写了 `Controller.shutdown()` 而不是 `controller.shutdown()`,或者一些类似的错误。 (2认同)