2012-11-12 23 views
0

我需要创建一个类,在画布上显示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),为什么其他元素会更改其索引?

+0

什么的Java UI库没有这个罐子使用? – mre

回答

1

这真的看起来像功课,所以我不会为你做,但给一些线索。

您可以使用getElementCount()方法来了解帧中矩形的当前数量。

创建一个GObjects列表,并在创建它们时用您的矩形填充它。 一旦达到10,则处理变得从屏幕除去使用

  • 删除矩形(GObject的gobj)
  • 除去第一元件,添加结束清单。

在这里,你:)

1

您需要存储到目前为止绘制的矩形列表。每次添加一个新的矩形时,如果列表已经有10个矩形长,请删除第一个矩形并添加一个新的矩形。然后,每次刷新显示时都需要重新绘制所有矩形,并使用双缓冲来防止屏幕闪烁。