【问题标题】:How can I manipulate childrens of a GridPane in JavaFX?如何在 JavaFX 中操作 GridPane 的子项?
【发布时间】:2018-11-11 18:55:39
【问题描述】:

我使用 JavaFX 制作了一个棋盘,并将所有图块设置为 GridPane 的子项,有没有办法可以访问这些图块并使用 GridPane 索引更改它们的属性?

我试图通过瓷砖矩阵访问它来更改一个瓷砖的颜色属性,但它不会更改 GridPane 中显示的瓷砖。

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

这是我的 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();

}

}

【问题讨论】:

    标签: java javafx children gridpane


    【解决方案1】:

    通过矩阵访问图块是可以的,但使用 getChildren() 也可以:您只需将节点类型转换为图块。除非您更改 Tile(继承自 Shape)的 fill 属性,否则瓷砖的颜色不会改变。 Tile 的构造函数确实调用了 setFill(),但 setColor() 没有。

    【讨论】:

    • 谢谢!我一直在挣扎,以至于我没有注意足够xD
    猜你喜欢
    • 2016-07-31
    • 1970-01-01
    • 2021-03-17
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    相关资源
    最近更新 更多