JavaFX - 如何在 GridPane 中获取 AnchorPane 并在其上添加文本?

JavaFX - How to get AnchorPane inside a GridPane and add Text on it?

我知道我可以使用以下代码在 GridPane 中添加 TextNode

Text text = new Text("Hello World");
gridPane.add(text, row, column);

但是我在 GridPane 的每个 rowscolumns 中都有 AnchorPane,这是在 SceneBuilder 的帮助下手动插入的,在 AnchorPane 我要添加 Text。比如获取 GridPane 的 children 并在其上添加 Text

我这样做了,但它不起作用:

for(int i = 0; i < row; i++){
  for(int j = 0; j < column; j++){
     Text text = new Text("Hello World!");
     gridPane.getChildren().add(text);
  }
}
 gridPane.getChildren().add(text);

text添加到第0行第0列的GridPane,即它与

具有相同的效果
 gridPane.add(text, 0, 0);

(实际上这不是100%相同,但在这种情况下差异并不重要。)

假设 GridPane 的每个子项都是 AnchorPane,您需要检索每个子项,将其转换为 Pane 并将 Text 添加到其子项列表:

for (Node child : gridPane.getChildren()) {
    Pane pane = (Pane) child;
    Text text = new Text("Hello World!");
    pane.getChildren().add(text);
}

当然,您可以使用不同的方法从列表中检索元素,而不是使用增强的 for 循环。列表中子项的顺序与 fxml 文件中 <GridPane> 元素的 <children> 元素中元素的顺序相匹配。 (这是它们在 SceneBuilder 的层次视图中出现的顺序。)

for(int i = 0; i < row; i++){
  for(int j = 0; j < column; j++){
     Text text = new Text("Hello World!");

    for(Node node : gridPane.getChildren()){
        Integer r = gridPane.getRowIndex(node);
        Integer c = gridPane.getColumnIndex(node);
        if(r!=null && r.intValue() == row && c != null && c.intValue() == column){
            AnchorPane anchorPane = (AnchorPane)node;
            anchorPane.getChildren().add(txt);
        }
    }

  }
}