问题描述
我正在制作一个基于错误感知"和进食的网格式游戏/模拟.我正在使用标签的 gridPane(称为 worldGrid
)来显示错误和食物的网格.当错误将细胞移向食物等时,这显然会不断更新.
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.
我目前有一个函数updateGrid(int col, int row, String cellContent)
,我想用在cellContent 中包含新文本的标签替换[row,col] 处的标签.
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.
我有以下工作
worldGrid.add(new Label(cellContent), row,col);
但是我担心这只是在当前标签之上添加一个标签,显然超过 100 次模拟迭代并不理想.
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:
worldGrid.getChildren().remove(row,col);
但是,当我尝试执行 add
行时,我得到了一个 IllegalArgumentException
.
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?
推荐答案
grid.add(node, col, row) 提供的col/row(注意先来col!)只是一个布局约束.这不提供任何访问列或行的方法,如二维数组中的插槽.所以要替换一个节点,你必须知道它的对象本身,例如在单独的数组中记住它们.
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.
然后你就可以调用 getChildren().remove(object)... 例如:
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);
这篇关于替换 JavaFX GridPane 中 (row,col) 处的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!