I initialized a GridPane through SceneBuilder and inside the controller I want to conditionally add a row to the GridPane. I do not want to store an int for how many rows I initialized, I want to be able to get the number of rows from the GridPane object. Is that possible?
Asked
Active
Viewed 1.4k times
4 Answers
11
Hej j will, try this method:
private int getRowCount(GridPane pane) {
int numRows = pane.getRowConstraints().size();
for (int i = 0; i < pane.getChildren().size(); i++) {
Node child = pane.getChildren().get(i);
if (child.isManaged()) {
Integer rowIndex = GridPane.getRowIndex(child);
if(rowIndex != null){
numRows = Math.max(numRows,rowIndex+1);
}
}
}
return numRows;
}
This worked for me.
Patrick

Michael Stauffer
- 298
- 1
- 4
- 15

Patrick
- 4,532
- 2
- 26
- 32
-
2Isn't rowIndex and rowEnd same numbers? Both are obtained with GridPane.getRowIndex(child). – Xdg Jan 03 '15 at 13:51
-
Yeah this doesn't work when I prorammatically add rows to a gridpane it still shows the initial row count, so it has issues – user176495 May 01 '17 at 04:16
-
I could have a valid GridPane with a non-empty set of rows, then call getRowConstraints() which is a list, call clear() to clear this list to remove all constraints and then when I call your getRowCount() get a return value of 0 even though the grid still has the same number of rows. – Graham Seed Jun 06 '23 at 16:21
7
In my case I used Java Reflections ( GridPane.java has private method getNumberOfRows() ):
Method method = gridPane.getClass().getDeclaredMethod("getNumberOfRows");
method.setAccessible(true);
Integer rows = (Integer) method.invoke(gridPane);

Vova Perebykivskyi
- 707
- 7
- 9
-
this works after I have added rows in code otherwise all I get is the initial allocation, which is dumb, poor form from the designers of the GridPane class – user176495 May 01 '17 at 04:19
3
With java 9, you can do this:
myGridPane.getRowCount();

Muzib
- 2,412
- 3
- 21
- 32
-
I believe this returns the row index of the element with the largest row index, so if you have gaps between rows, this doesn't return the number of rows. – Jack J Aug 23 '20 at 20:46