我可以在Java中使用FOR循环绘制n个矩形吗?

时间:2018-06-21 16:04:45

标签: java for-loop paintcomponent repaint

如何使用for-Loop在Java中绘制(25 * 25)个矩形,如何使用或替换下面的代码?

if (drawRectangles == 1) {
    graphics.fillRect(430, 428, 25, 25);
}

if (drawRectangles == 2) {graphics.fillRect(430, 428, 25, 25);
    graphics.fillRect(460, 428, 25, 25);
}

if (drawRectangles == 3) {
    graphics.fillRect(430, 428, 25, 25);
    graphics.fillRect(460, 428, 25, 25);
    graphics.fillRect(490, 428, 25, 25);
}

if (drawRectangles == 4) {
    graphics.fillRect(430, 428, 25, 25);
    graphics.fillRect(460, 428, 25, 25);
    graphics.fillRect(490, 428, 25, 25);
    graphics.fillRect(520, 428, 25, 25);
}

1 个答案:

答案 0 :(得分:2)

for的理解是许多语言的组成部分。

Java教程:docs.oracle.com/../tutorial/../for

寻找规则的增量,循环是理想的选择。

您每次将x增加30。

for(int inc = 0; inc  < drawRectangles; inc ++){
    x = 430 + (30 * inc)
    ...
    graphics.fillRect(x, y, x_size, y_size);
}

考虑对静态对象使用变量。它使您的代码更直观,并使更新和维护变得更加容易。