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

…衆ロ難τιáo~ 提交于 2020-08-25 10:54:28

问题


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);
    }
}

回答1:


How about

int[][] 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] ;
    }
}


来源:https://stackoverflow.com/questions/31145884/javafx-iterate-gridpane-nodes-per-row-read-nodes-of-gridpane-per-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!