如何添加 5x5 table 的矩形

How to add 5x5 table of rectangle shape

我刚加入并开始学习 JavaFX,但在如何添加 5x5 table 的矩形上有颜色时遇到了问题。这是我的进度:

public void start(Stage primaryStage) {
    GridPane grid = new GridPane();
    Random rand = new Random();
    ArrayList<String> colors = new ArrayList<String>();

    colors.add("ff0000");//red
    colors.add("#008000");//green
    colors.add("#0000ff");//blue
    colors.add("#ffff00");//yellow




    int row = 0;
    int col = 0;

    for (int i = 0; i < 26; i++) {
        Rectangle rect = new Rectangle(100, 100, 50, 50);
        rect.setFill(Color.web(colors.get(rand.nextInt(4))));
        rect.setStroke(Color.BLACK);

        grid.add(rect, row, col);
        if (row < 4) {
            row++;
        } 
        if (col < 4) {
            col++;
        }
    }

    grid.setAlignment(Pos.CENTER);
    Scene scene = new Scene(grid, 500, 500);

这是输出:

我希望它看起来像这样:

按如下方式编写循环:

for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; ++)
        Rectangle rect = new Rectangle(100, 100, 50, 50);
        rect.setFill(Color.web(colors.get(rand.nextInt(4))));
        rect.setStroke(Color.BLACK);    
        grid.add(rect, i, j);
    }
}

考虑执行 outer/inner 循环以正确索引行和列:

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            Rectangle rect = new Rectangle(100, 100, 50, 50);
            rect.setFill(Color.web(colors.get(rand.nextInt(4))));
            rect.setStroke(Color.BLACK);
            grid.add(rect, i, j);
       }
    }

为了更好地理解为什么会这样,请尝试在 for 循环的顶部打印 rowcol 值,而不是在循环中打印 ij 值这个代码。然后你就可以看到差异了。

在循环的前 4 次迭代中,您同时递增 rowcolumn,而在所有其他迭代中,您根本不递增它们,而是将矩形放在右下角的单元格中。此外,您的循环进行了 26 次迭代,而不是 25 = 5*5.

要更正错误,您需要仅在到达行尾时递增行,同时将列重置为 0:

final int columns = 5:
final int rows = 5
int row = 0;
int column = 0;

for (int i = 0; i < (columns * rows); ++i) {
    Rectangle rect = new Rectangle(100, 100, 50, 50);
    rect.setFill(Color.web(colors.get(rand.nextInt(4))));
    rect.setStroke(Color.BLACK);

    grid.add(rect, col, row);

    ++column; // move to right

    // if we exceed the available horizontal space, start new row
    if (column >= columns) {
        column = 0;
        row++;
    }
}

或者,您可以使用截断除法和取余运算符的结果从 i

计算 column/row
for (int i = 0; i < (columns * rows); ++i) {
    row = i / columns;
    column = i % columns;

通常情况下,其他答案中演示的嵌套循环会更可取,但我会提供一些替代方案并解释您哪里出错了。