如何访问网格窗格中的控件?

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

我在 java fxml 文件中定义了一个网格窗格,如下所示:

<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>

网格大小为 3 x 3,每个单元格中都有一个标签。是否可以循环遍历网格并更改每个标签的文本,如下面的伪代码所示:

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

可以

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

假设 gridPane.setGridLinesVisible( false );

但是,当 gridPane.setGridLinesVisible( true ) 时,会向 gridPane 的子列表添加一个额外的 gridLinesGroup 的类型)。在这种情况下,您可以检查 class 类型:

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

请注意 gridLinesVisible 属性 仅用于调试目的。还有其他选项可以设置 GridPane 的样式。