JavaFx Controller:检测阶段何时关闭

时间:2017-06-08 15:06:39

标签: java javafx-8

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

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

我在控制器类中尝试:

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

但它没有效果。

1 个答案:

答案 0 :(得分:8)

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

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

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

public dynamic MyAction() // Dynamic
public object MyAction() // Object
{
    return new {
        AZ = new StateObj(), // Insert your state type here
        NH = new StateObj()
    }
}

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

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

同样,退出应用程序可能不是(或可能不应该)是控制器的责任(它是创建窗口或管理应用程序生命周期的类的责任),所以如果你真的当窗口关闭时需要强制退出,你可能会将其移动到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();
    }
}