Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我的窗格有空的父项和空的场景?_Java_Javafx - Fatal编程技术网

Java 为什么我的窗格有空的父项和空的场景?

Java 为什么我的窗格有空的父项和空的场景?,java,javafx,Java,Javafx,我不熟悉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"

我不熟悉
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>
//主目录中的代码
父根=FXMLLoader.load(getClass().getResource(“sample.fxml”);
场景=新场景(根,800600);
//Fxml代码
当我调用
scene.getRoot()
时,我会得到在fxml中创建的窗格。 但是调用
pane.getScene()
pane.getParent()
返回空值

我是不是想的顺序不对?
getParent()
getScene()
是否应该为null,因为窗格没有场景,而场景有根? 比如说一个舞台有一个场景

如果是,, 我是否可以使用该窗格访问将此窗格作为其子窗格的场景或父级

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

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

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中的控制器,请不要使用静态
FXMLLoader.load()
方法,而是创建
FXMLLoader
的实例。加载
fxml
文件后,使用
getController()
方法访问控制器。如果我不必等待一个半小时发布问题,我会这样做。不管怎样,贴出了新问题,谢谢你的回答。