我需要創建一個類,在畫布上顯示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