我有一个名为 modSelectorScene 的场景,基于场景生成器中制作的 fxml,其根元素是 ScrollPane。 ScrollPane 包含一个 VBox,VBox 包含几个 TitledPanes,每个 TitledPanes 包含一个 AnchorPane,每个 AnchorPane 又包含几个 Button。
当我尝试将 modSelectorScene.lookup() 与每个按钮的 fx:id 一起使用以将按钮分配给代码中的 Button 对象时,问题就开始了 - 每个按钮都显示为 null。我发现我可以将 fx:id 分配给 ScrollPane 并查找它,但除此之外别无他法。如果我将 ScrollPane 包装在 AnchorPane 中,并将其中一个按钮移动到 AnchorPane 中,我就可以使用查找方法正常访问它。
因此,我现在正在考虑的解决方案涉及在 ScrollPane 及其内部的所有内容上交替调用 getContent() 和 getChildren() ,以挖掘我的方式并以这种方式获取我的按钮。这可行,但不是很……优雅。所以我想知道为什么按钮和所有其他元素在 ScrollPane 后面时对于查找方法来说是不可见的,以及是否有任何方法可以解决这个问题。
这是一个例子:
modSelectorScene = new Scene(FXMLLoader.load(getClass().getResource("Dialog/ModSelector.fxml")));
...
ScrollPane modScrollPane = (ScrollPane) modSelectorScene.lookup("#modScrollPane");
Button modStr = (Button) modSelectorScene.lookup("#modStr");
例如,尝试向 modStr 添加 EventHandler 会引发 NullPointerException,但 ScrollPane 已按预期分配。即使直接位于其内部的 VBox 在查找时也会返回 null。
最佳答案
布局似乎具有 getContent()
(而不是 getChildren()
)方法,如 ScrollPane
和 TitledPane
>,查找将在场景显示后进行。所以你可以尝试将查找代码包装到runnable中:
Platform.runLater(() ->
{
// lookup code
});
关于ScrollPane 和 TitledPane 的 JavaFX 查找问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31577907/