我想要检索 Gridpane 中一个特定单元格的内容。我已经将按钮放置在单元格中,并使用了相应的 ID 进行标识。
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;
}
label
上实现这个功能? - Mayur PatelmyGridPane.getChildren().get(i*8+j)
返回类型是一个对象,因此您必须进行类型转换,在我的情况下是:
(StackPane) (myGridPane.getChildren().get(i*8+j))
我在这个问题的解决方案中遇到了一些麻烦,因为方法 GridPane.getColumnIndex(Node node)
可能会在第一行或第一列(当索引实际上是0时)返回null
。因此,我使用了包装类Integer
进行处理,并得出了以下解决方案。希望对其他遇到同样问题的人有所帮助。
private Node getNodeFromGridPane(GridPane gridPane, int col, int row) {
ObservableList<Node> children = gridPane.getChildren();
for (Node node : children) {
Integer columnIndex = GridPane.getColumnIndex(node);
Integer rowIndex = GridPane.getRowIndex(node);
if (columnIndex == null)
columnIndex = 0;
if (rowIndex == null)
rowIndex = 0;
if (columnIndex == col && rowIndex == row) {
return node;
}
}
return null;
}
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;
}
}
如在一个重复的帖子中所说,您可能会遇到与选定答案(getNodeFromGridPane)有关的性能问题。
以下是克服该问题的方法:https://dev59.com/jGEi5IYBdhLWcg3w7_7P#65386693 但是,总结一下:
1. 使用双维数组:
private Node[][] gridPaneArray = null;
private void initializeGridPaneArray()
{
this.gridPaneArray = new Node[this.gridModel.getLines() [this.gridModel.getColumns()];
for(Node node : this.mainPane.getChildren())
{
this.gridPaneArray[GridPane.getRowIndex(node)][GridPane.getColumnIndex(node)] = node;
}
}
Node n = this.gridPaneArray[x][y]; // and cast it to any type you want/need