0

I know I can add Text or Node inside GridPane with the Following code

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

But I have AnchorPane inside every rows and columns of GridPane which is manually inserted by the help of SceneBuilder, inside the AnchorPane I want to add the Text. Something like getting the children of GridPane and add the Text on it.

I do it like this but it doesn't work:

for(int i = 0; i < row; i++){
  for(int j = 0; j < column; j++){
     Text text = new Text("Hello World!");
     gridPane.getChildren().add(text);
  }
}
fabian
  • 80,457
  • 12
  • 86
  • 114
Polar
  • 3,327
  • 4
  • 42
  • 77

2 Answers2

0
 gridPane.getChildren().add(text);

adds text to the GridPane at row 0, column 0, i.e. it has the same effect as

 gridPane.add(text, 0, 0);

(Actually this is not 100% the same, but the difference is unimportant in this context.)

Assuming every child of the GridPane is a AnchorPane, you need to retrieve every child, cast it to Pane and add the Text to it's child list:

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

Of course you could use different approaches for retrieving elements from a list instead of the enhances for loop. The order of the children in the list matches the order of the elements in the <children> element of the <GridPane> element in the fxml file. (This is the order they appear in in the hierarchy view of SceneBuilder.)

fabian
  • 80,457
  • 12
  • 86
  • 114
  • I'm using `AnchorPane` not `Pane` and the result is same as what I'm having right now. It's like a special character in random place of `GridPane`. – Polar Jul 06 '18 at 08:23
  • @KrixMuxDeadpool `Pane` is the supertype of `AnchorPane` where `getChildren`is made`public`. Using `Pane` or `AnchorPane` does not make a difference as long as every child of the GridPane is a AnchorPane. The code above does exactly what you wanted as long as there are only anchorpanes in the grid.I cannot help you with the other issue, since you haven't posted any details about the children of the `GridPane` and the time when your method is invoked. I assume you'd be better of creating both the `AnchorPane`s and the `Text` elements they are supposed to contain to the `gridPane` via your loop. – fabian Jul 06 '18 at 08:31
0
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);
        }
    }

  }
}
Polar
  • 3,327
  • 4
  • 42
  • 77