JavaFX:如何在初始化期间从控制器获取舞台? [英] JavaFX: How to get stage from controller during initialization?

查看:37
本文介绍了JavaFX:如何在初始化期间从控制器获取舞台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的控制器类中处理舞台事件(即隐藏).所以我所要做的就是通过

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

和之前

Scene scene = new Scene(root);
stage.setScene(scene);

因此 .getScene() 返回 null.

thus .getScene() returns null.

我自己找到的唯一解决方法是向 myPane.sceneProperty() 添加一个侦听器,当它不为 null 时,我得到场景,将其添加到它的 .windowProperty() 中!该死的!我最终检索阶段的侦听器处理.这一切都以设置所需的侦听器来进行事件结束.我觉得听众太多了.这是解决我问题的唯一方法吗?

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?

推荐答案

初始化后可以通过getController()FXMLLoader中获取控制器的实例,但是你需要实例化一个 FXMLLoader 而不是使用静态方法.

You can get the instance of the controller from the FXMLLoader after initialization via getController(), but you need to instantiate an FXMLLoader instead of using the static methods then.

我会在调用 load() 之后直接传递给控制器​​:

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:如何在初始化期间从控制器获取舞台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆