Replace node with (row, col) in JavaFX GridPane

I am making a grid-style game / simulation based on the โ€œfeelโ€ and eating errors. I use gridPane (called worldGrid) shortcuts to show grid errors and food. This, obviously, will be constantly updated when an error moves cells towards food, etc.

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

I have the following that works

worldGrid.add(new Label(cellContent), row,col);
However, I'm worried that this is just adding a label on top of the current label and, obviously, over 100 simulation iterations that are not perfect.

I tried this before adding a label:

worldGrid.getChildren().remove(row,col);

However, when I try to make a string, addI get IllegalArgumentException.

Any ideas on how to do this? Or even better, any ideas on how best to show an ever-changing grid that will ultimately use sprites instead of text?

+4
source share
3 answers

Col / row provided by grid.add (node, col, row) (ATTENTION comes col first!) Is only a layout constraint. This does not provide any means of accessing columns or rows, such as slots in a two-dimensional array. Therefore, to replace a node, you must know its object yourself, for example. remember them in a separate array.

getChildren(). remove (object)... :

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);
+11

Jens-Peter, , GridPane getColumnIndex getRowIndex node.

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

, GridPane , , .

+1

getChildren(). remove() , gridpane . , node. clearConstraints().

0

All Articles