How can I access a control that's in a grid pane?

1.2k views Asked by At

I have defined a grid pane in a java fxml file as follows:

<GridPane fx:id="grid" gridLinesVisible="true" prefHeight="256" prefWidth="256">

  ...

  <children>
    <Label maxHeight="1.8" maxWidth="1.8" />
    <Label maxHeight="1.8" maxWidth="1.8" GridPane.columnIndex="1" />
    <Label maxHeight="1.8" maxWidth="1.8" GridPane.columnIndex="2" />
    <Label maxHeight="1.8" maxWidth="1.8" GridPane.rowIndex="1" />
    <Label maxHeight="1.8" maxWidth="1.8" GridPane.columnIndex="1" GridPane.rowIndex="1" />
    <Label maxHeight="1.8" maxWidth="1.8" GridPane.columnIndex="2" GridPane.rowIndex="1" />
    <Label maxHeight="1.8" maxWidth="1.8" GridPane.rowIndex="2" />
    <Label maxHeight="1.8" maxWidth="1.8" GridPane.columnIndex="1" GridPane.rowIndex="2" />
    <Label maxHeight="1.8" maxWidth="1.8" GridPane.columnIndex="2" GridPane.rowIndex="2" />
  </children>

  ...

</GridPane>

The grid is 3 x 3 and has a label in each of its cells. Is it possible to loop through the grid and change the text for each label as shown in the pseudo code below:

for (cell : grid)
{
  cell.label.setText("x");
}
1

There are 1 answers

2
Uluk Biy On BEST ANSWER

Can be

for ( Node node : gridPane.getChildren() )
{
    (( Label ) node).setText( "x" );
}

Assuming that gridPane.setGridLinesVisible( false );

However when the gridPane.setGridLinesVisible( true ), an additional gridLines (type of Group) is added to gridPane's children list. In this case you may to check for class types:

for ( Node node : gridPane.getChildren() )
{
    if(node instanceof Label)
        (( Label ) node).setText( "x" );
}

Note that the gridLinesVisible property is for debugging purposes only. There are other options to style GridPane.