这里有一些问题。
您的for loop 不会执行任何迭代,因为您的条件是x > 10 而不是x < 10。
将第一行改为:
for (int x = 0; x>10;x++){
收件人:
for (int x = 0; x < 10; x++) {
此外,您每次迭代都将y 重置为 180,因此一旦您的循环开始,所有矩形将被绘制在彼此的顶部。在循环外声明y,或使用x 计算矩形位置。
像这样:
int y = 180;
for (int x = 0; x < 10; x++) {
graph2D.drawRect(170, y, 20, 50);
y = y + 45;
}
或者像这样:
for (int x = 0; x < 10; x++) {
graph2D.drawRect(170, (x * 45) + 180, 20, 50);
}
上面的数学(x * 45) + 180是一种超级简单的说法,即第一个矩形将在(x * 45) + 180 = 0 + 180 = 180,第二个将在(x * 45) + 180 = 45 + 180 = 225等等。
要更改矩形的颜色,您需要创建一个 Colors 列表或数组,并在每次迭代中使用列表中的不同 Color。
//Make the list
Color[] colors = {Color.black, Color.blue, Color.cyan, Color.darkGray,
Color.green, Color.lightGray, Color.magenta, Color.magenta,
Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
//Draw each rectangle
for (int x = 0; x < 10; x++) {
//Change the color
g.setColor(colors[x]);
//Draw the rectangle
graph2D.drawRect(170, (x * 45) + 180, 20, 50);
}
当然,如果您希望颜色是随机的,您可以考虑使用 Random 类,并生成一个介于 0 和 colors 数组长度之间的随机数。另请注意,我使用x 作为colors 数组的索引,如果您的循环将x 递增到高于数组中的颜色数,您将得到一个ArrayIndexOutOfBoundsException。
我还假设您将Graphics 的实例命名为g,因为大部分时间都是这样做的。