JavaFX类控制器场景参考 [英] JavaFX class controller scene reference

查看:150
本文介绍了JavaFX类控制器场景参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从关联的类控制器获取FXML加载文件的Scene对象。

Is there any way of getting the Scene object of an FXML loaded file from the associated class controller.

我正在做这样的事情:

@FXML
private AnchorPane anchor; 

Scene scene = anchor.getScene();

但是我想要一个不引用AnchorPane控件的解决方案。

but i'd like a solution that does not reference the AnchorPane control.

推荐答案

为什么不呢?控制器是一个抽象类,除非你故意让他知道,否则他不会知道UI。

Why not? Controller is an abstract class, he's not aware about UI unless you deliberately make him know.

节点(包括AnchorPane)是另一个故事,它们几乎不存在于场景图之外。因此,向Node询问他的父母或场景是完全没问题的。

Nodes (inlcuding AnchorPane) are another story, they hardly exists outside for scenegraph. So it's perfectly fine to ask Node about his parent or scene.

如果您仍想单独处理,则有下一种方法:

If you still want to handle that separately there are next approaches:


  1. 您可以创建自定义控制器并在加载后设置场景。请注意,当时 initialize()被称为尚未初始化。

public class MyController {
    private void Scene scene;
    public void setScene(Scene scene) { this.scene = scene; }

}

// loading code
FXMLLoader fxmlLoader = new FXMLLoader();
AnchorPane root = (AnchorPane) fxmlLoader.load(getClass().getResource("MyApp.fxml"));
MyController myController = (MyController) fxmlLoader.getController();
myController.setScene(scene);


  • 您可以创建一个自定义fxml控件,它将包含控制器,他只需调用 getScene()为自己。请在此处查看示例: https://stackoverflow.com/a/10718683/1054140

  • You can create a custom fxml control which will incorporate controller and he can just call getScene() for itself. See an example here: https://stackoverflow.com/a/10718683/1054140

    这篇关于JavaFX类控制器场景参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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