JavaFX: Get Node by row and column
The above answer from @invariant is totally correct but for some people that do it that way, there may be performances issues, especially with GridPanes that contain many elements. And also when working with loops (iterating over all the elements of a GridPane).
What I suggest you is to initialize a static array of all your element/nodes contained within the grid pane. Then use this array to get the nodes you need.
i.e.
1. have a double dimensional array :
private Node[][] gridPaneArray = null;
2. Call a method like so during the initialization of your view :
private void initializeGridPaneArray()
{
this.gridPaneArray = new Node[/*nbLines*/][/*nbColumns*/];
for(Node node : this.mainPane.getChildren())
{
this.gridPaneArray[GridPane.getRowIndex(node)][GridPane.getColumnIndex(node)] = node;
}
}
3. Get your node
Node n = this.gridPaneArray[x][y]; // and cast it to any type you want/need
I don't see any direct API to get node by row column index, but you can use getChildren
API from Pane
, and getRowIndex(Node child)
and getColumnIndex(Node child)
from GridPane
//Gets the list of children of this Parent.
public ObservableList<Node> getChildren()
//Returns the child's column index constraint if set
public static java.lang.Integer getColumnIndex(Node child)
//Returns the child's row index constraint if set.
public static java.lang.Integer getRowIndex(Node child)
Here is the sample code to get the Node
using row and column indices from the GridPane
public Node getNodeByRowColumnIndex (final int row, final int column, GridPane gridPane) {
Node result = null;
ObservableList<Node> childrens = gridPane.getChildren();
for (Node node : childrens) {
if(gridPane.getRowIndex(node) == row && gridPane.getColumnIndex(node) == column) {
result = node;
break;
}
}
return result;
}
Important Update: getRowIndex()
and getColumnIndex()
are now static methods and should be changed to GridPane.getRowIndex(node)
and GridPane.getColumnIndex(node)
.