从Gridpane中删除ImageView

时间:2017-07-13 13:26:57

标签: java user-interface gridpane

我用Java编写游戏。它有点像迷宫。如果玩家点击网格面板上的单元格,则玩家图像会移动到那里,我正在努力将玩家图像从旧位置移除。

以下是我创建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));
        }
    }

以下是我如何在OnClickEvent上绘制一个Player

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

我的基本问题是:如何删除GridPane上的Player Imageview?

非常感谢, 丹尼尔

1 个答案:

答案 0 :(得分:1)

这是你可以尝试的东西。每当您移动播放器时,移除目的地的当前图像,并将播放器图像添加到目的地。同时从之前的位置删除播放器图像,然后在其中添加图像。这是通用语法:

gridPane.getChildren().remove(currImg); 
gridPane.add(newImg, 1,0);

请注意,您需要引用要添加和删除的图像(播放器,空置)。