【问题标题】:Why does my pane have null Parent and null Scene?为什么我的窗格有 null Parent 和 null Scene?
【发布时间】:2017-09-03 17:24:07
【问题描述】:

我是 JavaFX 的新手,我想知道为什么我在我的 fxml 代码中创建的窗格没有父级和场景。

这是代码;

// Code in Main
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
Scene scene = new Scene( root, 800, 600);

// Fxml code
<Pane fx:controller="sample.Controller" fx:id="pane"
      xmlns:fx="http://javafx.com/fxml">
</Pane>

当我调用scene.getRoot() 时,我得到了我在 fxml 中创建的窗格。 但是调用pane.getScene()pane.getParent() 返回一个空值。

我是不是按错误的顺序思考这个问题? getParent()getScene() 是否应该为空,因为窗格没有场景但场景有根? 例如一个舞台有一个场景?

如果是这样, 有没有办法让我使用该窗格访问以该窗格作为其子级的场景或父级?

(我还希望 scene.getRoot() 返回父级而不是窗格,但我猜这与命名有关?)

【问题讨论】:

    标签: java javafx


    【解决方案1】:

    在 root 上调用 getParent() 将始终返回 null,因为在这种情况下,root 是 SceneGraph 中最顶层的元素。在将Pane 添加到Scene 之前调用getScene() 也会返回null,因为Pane 组件上没有设置场景属性。

    Parent root = FXMLLoader.load(getClass().getResource("test.fxml"));
    System.out.println("Root getParent(): " + root.getParent());
    System.out.println("Root getScene() before Scene: " + root.getScene());
    
    Scene scene = new Scene(root, 600, 600);
    System.out.println("Scene getRoot(): " + scene.getRoot());
    System.out.println("Root getScene() after Scene: " + root.getScene());
    
    stage.setScene(scene);
    stage.show();
    

    输出

    Root getParent(): null
    Root getScene() before Scene: null
    Scene getRoot(): StackPane@547a5be4[styleClass=root]
    Root getScene() after Scene: javafx.scene.Scene@24fd3643
    

    【讨论】:

    • 我怎样才能从控制器使用窗格访问场景呢?我必须在初始化时执行此操作,因为我正在尝试将 onKeyPressed() 添加到场景中,并且在 Main 中执行此操作不会让我与 Controller 中的内容进行交互。
    • 我已经回答了你的第一个问题。不要编辑现有问题。如果您有不相关的问题,请接受答案并提出另一个问题。
    • 如果您需要在 Main 中访问 Controller,则不要使用静态 FXMLLoader.load() 方法,而是创建 FXMLLoader 的实例。加载fxml 文件后,使用getController() 方法并访问Controller。
    • 如果我不必等待一个半小时来发布问题,我会这样做。无论如何,发布了新问题,感谢您的回答。
    猜你喜欢
    • 2017-04-02
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 2011-04-16
    • 2016-12-23
    • 2010-10-22
    相关资源
    最近更新 更多