How to dynamically remove nodes in JavaFx

2.6k Views Asked by At
@FXML AnchorPane gamePane;

public void gameStart() {
    if(!Started) {
        board = new Board();
        stones = new Circle[8][8];
        newTurn();
        applyBoard();
        Started = true;
    }
    else {
        DestroyBoard(); // <--- Erase all the stones 
        board = new Board();
        stones = new Circle[8][8];
        newTurn();
        applyBoard();
    }
}

public void applyBoard() { 
    for(int i = 0; i < board.boardsize; i++) {
        for(int j = 0; j < board.boardsize; j++) {
            if(board.board[i][j] != board.EMPTY) {
                if(board.board[i][j] == board.BLACK) {
                    stones[i][j] = new Circle(155 + 90 * j, 85 + 90 * i, 40);
                    stones[i][j].setFill(Color.BLACK);
                    gamePane.getChildren().add(stones[i][j]);
                }
                else if(board.board[i][j] == board.WHITE) {
                    stones[i][j] = new Circle(155 + 90 * j, 85 + 90 * i, 40);
                    stones[i][j].setFill(Color.WHITE);
                    gamePane.getChildren().add(stones[i][j]);
                }
            }
        }
    }
}
public void DestroyBoard() { // <---Test Function and not worked!!
    gamePane.getChildren().remove(stones[3][3]);
}

I Tried to make if press start button again then all stones on board erased and start a new game. As a first step I tried to erase one basic stone, but I can't delete any of stone on the board. What should I do to solve that?

1

There are 1 best solutions below

4
On

The stones are stored in an ObservableList within the gamePane container, which you access with the getChildren() method. The list has a very helpful clear() method that removes all items in the list.

So if you are just looking to remove all the stones from gamePane, just call this method:

gamePane.getChildren().clear();