gpt4 book ai didi

java - JavaFX 中正方形的网格 Pane

转载 作者:行者123 更新时间:2023-11-30 08:40:56 25 4
gpt4 key购买 nike

我是 JavaFX 的新手,我正在尝试制作棋盘。我首先想开始制作一个填充随机颜色的正方形网格数组。我不确定为什么,但方 block 没有填满网格的其余部分。我还想使用约束来设置网格的高度和宽度。

int rowNum = 10;
int colNum = 10;
int gridHeight = 10;
int gridWidth = 10;

public void start(Stage primaryStage) {
GridPane grid = new GridPane();

//grid.getColumnConstraints().add(new ColumnConstraints(gridWidth));
//grid.getRowConstraints().add(new RowConstraints(gridHeight));

Random rand = new Random();
Color[] colors = {Color.BLACK, Color.BLUE, Color.GREEN, Color.RED};

int n = rand.nextInt(4)+1;
for(int row = 0; row < rowNum; row++){
for(int col = 0; col < colNum; col++){
Rectangle rec = new Rectangle();
rec.setWidth(2);
rec.setHeight(2);
rec.setFill(colors[n]);
GridPane.setRowIndex(rec, row);
GridPane.setColumnIndex(rec, col);
grid.getChildren().addAll(rec);
}
}

Scene scene = new Scene(grid, 350, 250);

primaryStage.setTitle("Grid");
primaryStage.setScene(scene);
primaryStage.show();
}

只有一个正方形出现在左上角。为什么会这样?

最佳答案

您需要将随机数生成步骤移到两个循环内,这样您就不会使用在进入循环之前已设置一次的相同颜色。此外,您不需要在该随机数生成器上加 1。允许的索引为 0-3。当您请求 nextInt() 并输入 4 时,这是排他性的,这意味着永远不会选择 4(这是 Color 数组所需要的)。

您的代码应如下所示:

for (int row = 0; row < rowNum; row++) {
for (int col = 0; col < colNum; col++) {
int n = rand.nextInt(4);
Rectangle rec = new Rectangle();
rec.setWidth(2);
rec.setHeight(2);
rec.setFill(colors[n]);
GridPane.setRowIndex(rec, row);
GridPane.setColumnIndex(rec, col);
grid.getChildren().addAll(rec);
}
}

关于java - JavaFX 中正方形的网格 Pane ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35367060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com