I made a Chess Board using JavaFX, and set all the tiles to be children of the GridPane, is there a way I can acess these tiles and change their properties using the GridPane index?
I tried to change the color property of one tile by acessing it by the matrix of tiles, but it doesn't change the tile displayed in the GridPane.
The .getChildren() method returns a list of nodes, and I can't acess the methods of the tile object once it became a node.
Here's my Tile Class:
package chess.Board;
import static chess.Chess.TILE_W;
import static chess.Chess.TILE_Y;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class Tile extends Rectangle{
private final int width = TILE_W;
private final int height = TILE_Y;
private final int x;
private final int y;
private Color color;
public void setColor(Color color) {
this.color = color;
}
public Color getColor(){
return this.color;
}
public Tile(Color c, int x, int y){
this.color = c;
this.x = x;
this.y = y;
setFill(c);
setHeight(this.height);
setWidth(this.width);
relocate(x*TILE_W, y*TILE_Y);
}
}
And Here is my Board class:
package chess.Board;
import static chess.Chess.HEIGHT;
import static chess.Chess.TILE_W;
import static chess.Chess.TILE_Y;
import static chess.Chess.WIDTH;
import javafx.scene.Parent;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
public class Board {
private Tile[][] tilesMatrix;
private void setMatrix(){
Tile[][] tilesCreator = new Tile[WIDTH][HEIGHT];
for(int y = 0; y < HEIGHT; y++){
for(int x = 0; x < WIDTH; x++){
if(y%2 == 0){
if(x%2 == 0)
tilesCreator[x][y] = new Tile(Color.ANTIQUEWHITE, x, y);
else
tilesCreator[x][y] = new Tile(Color.DARKGREEN, x, y);
}
else{
if(x%2 == 0)
tilesCreator[x][y] = new Tile(Color.DARKGREEN, x, y);
else
tilesCreator[x][y] = new Tile(Color.ANTIQUEWHITE, x, y);
}
}
}
this.tilesMatrix = tilesCreator;
}
public Tile[][] getMatrix(){
return this.tilesMatrix;
}
public Parent getBoard(){
GridPane board = new GridPane();
board.setPrefSize(WIDTH*TILE_W, HEIGHT*TILE_Y);
for(int y = 0; y < HEIGHT; y++)
for(int x = 0; x < WIDTH; x++)
board.add(getMatrix()[x][y], x, y);
return board;
}
public Board(){
setMatrix();
}
}
Accessing the tiles by the matrix is OK, but using getChildren() is OK too: you just have to type cast the Node to a Tile. The color of the tiles won't change unless you change the fill property of the Tile (inherited from Shape). The constructor of Tile does call setFill(), but setColor() doesn't.