2012-11-12 24 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個矩形長,請刪除第一個矩形並添加一個新的矩形。然後,每次刷新顯示時都需要重新繪製所有矩形,並使用雙緩衝來防止屏幕閃爍。