Get the number of rows in a JavaFX GridPane?
Asked Answered
O

4

9

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?

Occupational answered 24/12, 2013 at 20:19 Comment(0)
P
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

Performance answered 24/12, 2013 at 21:6 Comment(3)
Isn't rowIndex and rowEnd same numbers? Both are obtained with GridPane.getRowIndex(child).Summons
Yeah this doesn't work when I prorammatically add rows to a gridpane it still shows the initial row count, so it has issuesDelrio
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.Divertissement
E
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);
Endodontics answered 1/10, 2016 at 13:30 Comment(1)
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 classDelrio
A
3

With java 9, you can do this:

myGridPane.getRowCount();
Atony answered 10/12, 2017 at 10:51 Comment(1)
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.Harquebus
D
0

This works for me

GridPane.getRowConstraints().size()
Disqualify answered 20/2, 2020 at 20:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.