JavaFX类控制器阶段/窗口引用 [英] JavaFX Class controller Stage/Window reference
本文介绍了JavaFX类控制器阶段/窗口引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法从关联的类控制器获取FXML加载文件的Stage / Window对象?
Is there any way of getting the Stage/Window object of an FXML loaded file from the associated class controller?
特别是,我有一个模态窗口的控制器我需要舞台来关闭它。
Particularly, I have a controller for a modal window and I need the Stage to close it.
推荐答案
我找不到一个优雅的解决方案。但我发现了这两种选择:
I could not find an elegant solution to the problem. But I found these two alternatives:
-
从场景中的节点获取窗口引用
Getting the window reference from a Node in the Scene
@FXML private Button closeButton ;
public void handleCloseButton() {
Scene scene = closeButton.getScene();
if (scene != null) {
Window window = scene.getWindow();
if (window != null) {
window.hide();
}
}
}
传递窗口加载FXML时作为控制器的参数。
Passing the Window as an argument to the controller when the FXML is loaded.
String resource = "/modalWindow.fxml";
URL location = getClass().getResource(resource);
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
Parent root = (Parent) fxmlLoader.load();
controller = (FormController) fxmlLoader.getController();
dialogStage = new Stage();
controller.setStage(dialogStage);
...
FormController必须实现setStage方法。
And FormController must implement the setStage method.
这篇关于JavaFX类控制器阶段/窗口引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文