ScrollPane 和 TitledPane 的 JavaFX 查找问题

JavaFX lookup issues with ScrollPane and TitledPane

我有一个名为 modSelectorScene 的场景,它基于在 Scene Builder 中制作的 fxml,其根元素是 ScrollPane。 ScrollPane包含一个VBox,VBox包含几个TitledPanes,每个TitledPanes包含一个AnchorPane,每个AnchorPane包含几个Button。

当我尝试将 modSelectorScene.lookup() 与每个按钮的 fx:id 一起使用以将按钮分配给代码中的 Button 对象时,问题就开始了——每个按钮都变成了空值。我发现我可以为 ScrollPane 分配一个 fx:id 并查找它,但没有别的。如果我将 ScrollPane 包装在一个 AnchorPane 中,然后将其中一个按钮移到 AnchorPane 中,我可以使用查找方法正常访问它。

所以我现在正在寻找的解决方案涉及交替调用 ScrollPane 上的 getContent() 和 getChildren() 以及其中的所有内容,以便深入挖掘并以这种方式获取我的按钮。这行得通,但不是很……优雅。所以我想知道为什么 Buttons 和所有其他元素在 ScrollPane 后面时对 lookup 方法不可见,以及是否有任何方法可以解决这个问题。

这是一个例子:

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 returns 查找时为空。

似乎对于具有 getContent()(而不是 getChildren())方法的布局,如 ScrollPaneTitledPane,查找将在场景显示后起作用。所以你可以尝试将查找代码包装成runnable:

Platform.runLater(() ->
{
    // lookup code
});

尝试在lookup(...)之前使用getContent():

titledPane.getContent().lookup("#id")