我正在 JavaFX 中制作一个游戏,我有 5x9 网格的 ImageView 和一些标签。当我尝试引用 label 时,我成功了。但是,当我尝试获取对 ImageView 的引用时,我得到 nullPointerException。
以下是声明 root 的方式:
FXMLLoader loaderTwo = new FXMLLoader(getClass().getResource("/game/levelTwo.fxml"));
Parent rootTwo = loaderTwo.load();
this.handlerTwo = loaderTwo.getController();
这是标签的 FXML 部分:
<Label fx:id="sunCountLabel" layoutX="121.0" layoutY="15.0" minHeight="72.2891845703125" prefHeight="88.0" prefWidth="203.0" text="Label">
<font>
<Font name="Gabriola" size="60.0" />
</font>
</Label>
ImageView 的 FXML 部分:
<ImageView fx:id="OneFive" fitHeight="180.0" fitWidth="180.0" layoutX="892.0" layoutY="102.0">
<effect>
<DropShadow height="1.0" radius="0.0" width="1.0" />
</effect>
<image>
<Image url="@../media/half.png" />
</image>
</ImageView>
这是我提到它们的地方:
this.root = this.map.getLevel(2).getRoot();
Label l = (Label)this.root.lookup("#sunCountLabel");
ImageView i = (ImageView)this.root.lookup("OneFive");
System.out.println(i==null);
l.setText("1999");
问题是 Label 工作正常,但 Imageview 给出 nullPointerException
我不明白为什么?
此外,场景加载完美,图像地址等没有问题。
最佳答案
您使用的选择器是类型选择器,即只有当节点从getTypeSelector
method返回“OneFive”
时,它才起作用。 。 ImageView
不会执行此操作。
您可能想使用 id 选择器。这需要您在选择器字符串的开头插入 #
:
ImageView i = (ImageView)this.root.lookup("#OneFive");
我强烈建议将 ImageView
注入(inject) Controller 中的字段,并通过 Controller 访问 ImageView
。另请注意,在某些情况下查找
不起作用。在 ScrollPane
中查找内容,例如在第一个布局传递之前不起作用,因为添加内容
的节点结构是在第一个布局传递期间创建的。
关于java - 获取对 FXML ImageView 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58611665/