如何在JavaFX中操纵GridPane的子级?

时间:2018-11-11 18:55:39

标签: java javafx children gridpane

我使用JavaFX制作了一个国际象棋棋盘,并将所有图块设置为GridPane的子代,是否可以使用GridPane索引访问这些图块并更改其属性?

我试图通过按图块矩阵访问一个图块来更改其颜色属性,但它并没有更改GridPane中显示的图块。

.getChildren()方法返回节点列表,一旦它成为节点,我就无法访问tile对象的方法。

这是我的图块课程:

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

}

}

这是我的董事会班级:

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

}

}

1 个答案:

答案 0 :(得分:0)

通过矩阵访问切片是可以的,但是使用getChildren()也是可以的:您只需键入将Node投射到Tile即可。除非更改了Tile的 fill 属性(从Shape继承),否则瓦片的颜色不会改变。 Tile的构造函数会调用setFill(),但不会调用setColor()。