0

我在 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");
}
4

1 回答 1

2

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

假设_gridPane.setGridLinesVisible( false );

然而,当 时gridPane.setGridLinesVisible( true ),一个额外的gridLines(类型Group)被添加到 gridPane 的子列表中。在这种情况下,您可以检查类类型:

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

请注意,该gridLinesVisible属性仅用于调试目的。GridPane 的样式还有其他选项。

于 2015-06-10T14:57:33.147 回答