javajavafxgridpane

JavaFX - Iterate GridPane nodes per row - Read Nodes of GridPane per row


I am creating an application using JavaFX 8. I change the content of a grid pane dynamically using drag/drop. I wish to iterate GridPane contents per row or per row/col. JavaFX allows adding nodes in a GridPane by specifying the row and column.

gridPane.add(node, col, row);

I would like to read the nodes of a GridPane on the same way, by specifying the row and column.
I would like to have something similar to the below source (the below code is not correct),

for(int row = 0; row < gridPaneHeight; row++) {
    for(int col = 0; row < gridPaneWidth; col++) {
        Node node = gridPane.get(col, row);
    }
}

Solution

  • How about

    Node[][] gridPaneNodes = new int[gridPaneWidth][gridPaneHeight] ;
    for (Node child : gridPane.getChildren()) {
        Integer column = GridPane.getColumnIndex(child);
        Integer row = GridPane.getRowIndex(child);
        if (column != null && row != null) {
            gridPaneNodes[column][row] = child ;
        }
    }
    

    (or, you could just keep track of which were placed in which cell when you put them there...)

    Then you can do

    for (int row = 0; row < gridPaneHeight; row++) {
        for(int col = 0; row < gridPaneWidth; col++) {
            Node node = gridPaneNodes[column][row] ;
        }
    }