【问题标题】:JavaFx Controller: detect when stage is closingJavaFx 控制器:检测阶段何时关闭
【发布时间】:2017-11-10 09:16:29
【问题描述】:

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

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

我尝试在控制器类中:

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

但是没有效果。

【问题讨论】:

    标签: java javafx-8


    【解决方案1】:

    仅从设计的角度来看,在控制器中将处理程序与舞台相关联并没有真正意义,因为舞台通常不是控制器所连接的视图的一部分。

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

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

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

    然后在你加载 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();
    

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

    public class Controller {
    
        // fields and event handler methods...
    
    
        public void shutdown() {
            // cleanup code here...
            System.out.println("Stop");
            action();
        }
    }
    

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

    【讨论】:

    • 有趣的答案。如果我按照程序进行,我在stage.setOnHidden中有问题controller.shutdown(),编译器告诉我它应该是静态的,如何在不解决的情况下解决它?
    • 你可能写了Controller.shutdown()而不是controller.shutdown(),或者一些类似的错误。
    猜你喜欢
    • 2016-02-29
    • 2019-03-28
    • 2012-08-20
    • 2012-04-30
    • 2012-07-13
    • 2014-12-24
    • 2015-08-03
    • 2014-04-21
    • 2014-04-07
    相关资源
    最近更新 更多