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


I am making a grid-style game/simulation based on bugs "sensing" and eating food. I am using a gridPane (called worldGrid) of labels to show the grid of bugs and food. This is obviously going to be constantly updated when a bug moves cells towards food etc.

I currently have a function updateGrid(int col, int row, String cellContent) which I want to replace the label at [row,col] with a label that has the new text in cellContent.

I have the follow which works

worldGrid.add(new Label(cellContent), row,col);

however im worried that that is just adding a label on top of the current label and obviously over 100 iterations of the simulation thats not ideal.

I have tried this before adding the label:


However I then get an IllegalArgumentException when trying to do the add line.

Any ideas on how to do this? Or even better, any ideas on how best to show a constantly changing grid that will eventually use sprites instead of text?

3/27/2016 8:01:45 PM

Accepted Answer

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.add(new Label("last"), 2, 2);
9/18/2016 4:56:39 AM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow