我想检索Gridpane中一个特定单元格的内容。我把按钮放在了细胞中
setConstraints(btt , 0 ,1 )
setConstraints(btt , 0 ,2 )
getChildren().add....
在我的情况下,GridPane.getChildren.get(10)
不好。我想直接进入单元格(4,2)并获取其内容。
好吧,我想如果没有解决方案从gridpane获取特定节点的是列和行索引,我有一个函数来做到这一点,
private Node getNodeFromGridPane(GridPane gridPane, int col, int row) {
for (Node node : gridPane.getChildren()) {
if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) {
return node;
}
}
return null;
}
假设你有一个8x8 girdPane,其中i
是行,j
是列,你可以写:
myGridPane.getChildren().get(i*8+j)
返回类型是一个对象,所以你必须抛出它,在我的例子中它是:
(StackPane) (myGridPane.getChildren().get(i*8+j))
您可以添加一个包含gridpane的每个子节点的列表,并且每个子节点的父节点必须有两个整数的行和列,因此您只需要遍历该列表并查看它是否具有正确的坐标! (您应该可以添加一个新类,以便存储这些坐标),这是我的解决方案的最小示例
import java.util.ArrayList;
import java.util.List;
import javafx.scene.Node;
import javafx.scene.layout.GridPane;
public class SpecialGridPane extends GridPane {
List<NodeParent> list = new ArrayList<>();
public void addChild(int row, int column, Node node) {
list.add(new NodeParent(row, column, node));
setConstraints(node, column, row);
getChildren().add(node);
}
public Node getChild(int row, int column) {
for (NodeParent node : list) {
if (node.getRow() == row && node.getColumn() == column)
return node.getNode();
}
return null;
}
}
class NodeParent {
private int row;
private int column;
private Node node;
public NodeParent(int row, int column, Node node) {
this.row = row;
this.column = column;
this.node = node;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
public Node getNode() {
return node;
}
}