我需要创建一个类,在画布上显示10个矩形,每个矩形都有一个随机的颜色和位置。当它达到11时,第一个矩形被替换为一个新的随机颜色和位置。第12个矩形取代第二个矩形框,依此类推。我正在使用acm.jar,http://jtf.acm.org/javadoc/student/index.html。当10个矩形到达时,在屏幕上替换矩形对象?
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,并且删除了元素(0),为什么其他元素会更改其索引?
什么的Java UI库没有这个罐子使用? – mre