我需要创建一个在 Canvas 上显示 10 个矩形的类,每个矩形都有随机的颜色和位置。当达到 11 时,第一个矩形将替换为新的随机颜色和位置。第 12 个矩形替换第 2 个矩形,依此类推。我为此使用 acm.jar http://jtf.acm.org/javadoc/student/index.html 。
import acm.graphics.*;
import acm.program.*;
import java.awt.Color;
import java.util.Random;
public class Rect extends GraphicsProgram
{
public void run()
{
final int width = 800;
final int height = 600;
final int boxWidth = 50;
final int maxBoxes = 10;
this.setSize(width, height);
Random random = new Random();
for(;;) {
int x = random.nextInt(width-boxWidth);
int y = random.nextInt(height-boxWidth);
Color c = new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
GRect r = new GRect(x, y, boxWidth, boxWidth);
r.setFilled(true);
r.setLocation(x, y);
r.setFillColor(c);
this.add(r);
this.pause(100);
}
}
}
我已经弄清楚如何使颜色随机,但我不知道如何用旧盒子替换盒子。
编辑:::---------------------------------------- ----------------------------------------------------
在下面的人的帮助下,我确实设法让它工作。新的 for 循环如下所示:
for(;;) {
int x = random.nextInt(width-boxWidth);
int y = random.nextInt(height-boxWidth);
Color c = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
GRect r = new GRect(boxWidth, boxWidth);
r.setFilled(true);
r.setLocation(x, y);
r.setFillColor(c);
add(r, x, y);
int n = getElementCount();
if (n>maxBoxes)
{
remove(getElement(0));
}
this.pause(100);
}
我不明白的一件事是为什么删除(getElement(0))起作用,元素被删除后如何更改其索引?如果我有 10 个元素 0-9,并且我删除了 element(0),为什么其他元素会更改其索引?
最佳答案
这看起来真的像家庭作业,所以我不会为你做,但会提供一些线索。
您可以使用 getElementCount() 方法来了解框架中当前矩形的数量。
创建 GObject 列表,并在创建矩形时将其填充到其中。 一旦你达到十,这个过程就变成了
- 使用remove(GObject gobj)从屏幕上删除矩形
- 删除第一个元素,添加到列表末尾。
你在这里:)
关于java - 当达到 10 个矩形时替换屏幕上的矩形对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13346403/