Replace a node at (row,col) in a JavaFX GridPane

a 夏天 提交于 2019-12-01 05:38:41
Jens-Peter Haack

The col/row provided by grid.add(node, col, row) (ATTENTION first comes col!) is only a layout constraint. This does not provide any means to access columns or rows like slots in a 2-dimensional array. So to replace a node, you have to know its object itself, e.g. remember them in a separate array.

Then you are able to call getChildren().remove(object)... e.g.:

GridPane grid = new GridPane();

Label first = new Label("first");
Label second = new Label("second");

grid.add(first,  1,  1);
grid.add(second,  2,  2);
second.setOnMouseClicked(e -> {
    grid.getChildren().remove(second);
    grid.add(new Label("last"), 2, 2);
});
box.getChildren().addAll(grid);
T-and-M Mike

I agree with Jens-Peter but I would add that you can use GridPane's getColumnIndex and getRowIndex to obtain a particular node's location.

For example ( this is in a component which extends GridPane ):

// set the appropriate label
for (Node node : getChildren()) {
    if (node instanceof Label
     && getColumnIndex(node) == column
     && getRowIndex(node) == row) {
        ((Label)node).setTooltip(new Tooltip(tooltip));
    }
}

in other words, go through all the nodes in the GridPane and check for a match of the conditions you want, in this case row and column.

You called getChildren().remove() method directly will cause the gridpane to go out of sync with the constraints. When you add, it also setup the constraint for the node. Add clearConstraints() method.

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