Как я могу манипулировать детьми GridPane в JavaFX? - PullRequest
0 голосов
/ 11 ноября 2018

Я создал шахматную доску, используя JavaFX, и установил все плитки как дочерние элементы GridPane. Есть ли способ, которым я могу получить доступ к этим плиткам и изменить их свойства с помощью индекса GridPane?

Я попытался изменить свойство цвета одной плитки, изменив его по матрице плиток, но это не изменило плитку, отображаемую в GridPane.

Метод .getChildren () возвращает список узлов, и я не могу получить доступ к методам объекта плитки, когда он стал узлом.

Вот мой класс плитки:

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 голосов
/ 12 ноября 2018

Доступ к плиткам по матрице - это нормально, но с помощью getChildren () тоже можно: вам нужно просто набрать приведение узла к плитке. Цвет плиток не изменится, если вы не измените свойство плитки fill (унаследованное от Shape). Конструктор Tile вызывает setFill (), а setColor () - нет.

...