问题描述
我想从我的控制器类处理阶段事件(即隐藏)。所以我要做的就是通过
添加一个监听器((阶段)myPane.getScene()。getWindow()) .setOn * whatIwant *(......);
但问题是初始化是在
之后立即开始的
父root = FXMLLoader.load(getClass()。getResource(MyGui.fxml));
之前
场景场景=新场景(根);
stage.setScene(场景);
因此.getScene()返回null。
我认为听众太多了。
这是解决我问题的唯一方法吗?
你可以从FXMLLoader获取控制器的实例在通过 getController()
初始化之后,你需要实例化FXMLLoader,而不是使用静态方法。
之后我将调用 load()
直接传递给控制器:
FXMLLoader loader = new FXMLLoader(getClass()。getResource(MyGui.fxml));
父root =(父)loader.load();
MyController controller =(MyController)loader.getController();
controller.setStageAndSetupListeners(stage); //或者你想做什么
I want to handle stage events (i.e. hiding) from my controller class. So all I have to do is to add a listener via
((Stage)myPane.getScene().getWindow()).setOn*whatIwant*(...);
but the problem is that initialization starts right after
Parent root = FXMLLoader.load(getClass().getResource("MyGui.fxml"));
and before
Scene scene = new Scene(root);
stage.setScene(scene);
thus .getScene() returns null.
The only workaround I found by myself is to add a listener to myPane.sceneProperty(), and when it becomes not null I get scene, add to it's .windowProperty() my !goddamn! listener handling which I finally retrieve stage. And it all ends with setting desired listeners to stage events.I think there are too many listeners.Is it the only way to solve my problem?
You can get the instance of the controller from the FXMLLoader after initialization via getController()
, but you need to instanciate an FXMLLoader instead of using the static methods then.
I'd pass the stage after calling load()
directly to the controller afterwards:
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:如何在初始化期间从控制器获取阶段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!