在JavaFX GridPane中替换(row,col)上的一个节点 [英] Replace a node at (row,col) in a JavaFX GridPane

查看:1284
本文介绍了在JavaFX GridPane中替换(row,col)上的一个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在基于感知和吃食物的错误进行网格式游戏/模拟。我正在使用一个gridPane(称为 worldGrid )的标签来显示错误和食物的网格。当一个错误将细胞移动到食物等时,这显然会不断更新。



我目前有一个函数 updateGrid(int col,int row ,String cellContent)我想用[row,col]中的标签替换在cellContent中具有新文本的标签。



我有以下作品

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

然而,我担心这只是在当前标签之上添加标签,显然超过100次迭代的模拟不太理想。



我在添加标签之前尝试过:

  worldGrid。 。的getChildren()除去(行,列); 

然而,我尝试时会得到一个 IllegalArgumentException 要做添加行。



有什么想法如何做到这一点?或者更好的是,有关如何最好地显示不断变化的网格的想法,最终会使用sprites而不是文本?

解决方案

由grid.add(node,col,row)提供的col / row(注意第一个来到col!)只是一个布局约束。这不提供任何方式来访问列或行,如2维数组中的插槽。所以要替换一个节点,你必须知道它的对象本身,例如记住它们在一个单独的数组。



然后你可以调用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);


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:

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

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?

解决方案

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

这篇关于在JavaFX GridPane中替换(row,col)上的一个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆