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

时间:2015-06-10 14:51:38

标签: java loops javafx fxml gridpane

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

1 个答案:

答案 0 :(得分:1)

可以

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

假设 gridPane.setGridLinesVisible( false );

但是当gridPane.setGridLinesVisible( true )时,其他gridLinesGroup类型)会添加到gridPane的子列表中。在这种情况下,您可以检查班级类型:

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

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

相关问题