I am programming a game in Java. It's kind of like a labyrinth. If a player clicks on a cell on a gridpane the player image moves there and I am struggling with removing the playerImage from the old position.
Here is how i am creating the imageViews:
private ImageView[][] initImages() {
int colcount = gridPane.getColumnConstraints().size();
int rowcount = gridPane.getRowConstraints().size();
imageViews = new ImageView[colcount][rowcount];
// bind each Imageview to a cell of the gridpane
int cellWidth = (int) gridPane.getWidth() / colcount;
int cellHeight = (int) gridPane.getHeight() / rowcount;
for (int x = 0; x < colcount; x++) {
for (int y = 0; y < rowcount; y++) {
//creates an empty imageview
imageViews[x][y] = new ImageView();
//image has to fit a cell and mustn't preserve ratio
imageViews[x][y].setFitWidth(cellWidth);
imageViews[x][y].setFitHeight(cellHeight);
imageViews[x][y].setPreserveRatio(false);
imageViews[x][y].setSmooth(true);
//add the imageview to the cell and
//assign the correct indicees for this imageview, so you later can use GridPane.getColumnIndex(Node)
gridPane.add(imageViews[x][y], x, y);
//the image shall resize when the cell resizes
imageViews[x][y].fitWidthProperty().bind(gridPane.widthProperty().divide(colcount));
imageViews[x][y].fitHeightProperty().bind(gridPane.heightProperty().divide(rowcount));
}
}
and here is how i draw a Player on a OnClickEvent
public RealGUI drawPlayer(int playerNumber, CellCoordinates coords) {
Image img = null;
switch (playerNumber) {
case 1:
img = new Image("/gui/img/Bob_trans.png");
break;
case 2:
// trans Bild Spieler 2
img = new Image("/gui/img/Bob_trans.png");
break;
default:
System.out.print("Problem mit Spielernummer");
}
ImageView newImgView = new ImageView();
newImgView.fitHeightProperty().bind(this.gridPane.heightProperty()
.divide(this.gridPane.getRowConstraints().size()));
newImgView.setImage(img);
this.gridPane.add(newImgView, coords.getX(), coords.getY());
return this;
}
My basic question is: How to I remove the Player Imageview on the GridPane?
Thank you very much, Daniel
Here's something you can try. Whenever you move a player, remove the current image at the destination and add the player image to the destination. Also remove the player image from the previous location and add an empty image there. Here's the generic syntax:
gridPane.getChildren().remove(currImg);
gridPane.add(newImg, 1,0);
Note that you need references to the images (players, empties) you are adding and removing.