gpt4 book ai didi

java - 如何访问网格 Pane 中的控件?

转载 作者:行者123 更新时间:2023-12-02 04:35:53 25 4
gpt4 key购买 nike

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

<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 ) 时,额外的 gridLines(Group 类型)会添加到 gridPane 的子列表中。在这种情况下,您可以检查类类型:

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

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

关于java - 如何访问网格 Pane 中的控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30759900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com