我想从我的 Controller 类处理阶段事件(即隐藏)。所以我所要做的就是添加一个像这样的监听器:
((Stage) myPane.getScene().getWindow()).setOn*whatIwant*(...);
但问题是初始化在这段代码之后立即开始:
Parent root = FXMLLoader.load(getClass().getResource("MyGui.fxml"));
在此代码之前:
Scene scene = new Scene(root);
stage.setScene(scene);
因此 getScene
返回 null。
我自己发现的唯一解决方法是向 myPane.sceneProperty
添加一个监听器,当它变为非空时,我得到场景,将其添加到它的 windowProperty
我的监听器处理这个我终于找回了舞台。这一切都以设置所需的监听器来暂存事件而告终。
我认为听众太多了。
这是解决我的问题的唯一方法吗?
最佳答案
初始化后,您可以通过getController()
从FXMLLoader
获取 Controller 的实例,但您需要实例化一个FXMLLoader
然后使用静态方法。
我会在调用 load()
之后直接将阶段传递给 Controller :
FXMLLoader loader = new FXMLLoader(getClass().getResource("MyGui.fxml"));
Parent root = (Parent)loader.load();
MyController controller = (MyController)loader.getController();
controller.setStageAndSetupListeners(stage); // or what you want to do
关于javafx - 如何在初始化期间从 Controller 获取阶段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56778679/