Substitute rectangle objects on screen when 10 rectangles are reached?
<p>I need to create a class that displays 10 rectangles on the canvas, each with a random color and position. When it reaches 11, the first rectangle is replaced with a new random color and position. 12th rect replaces the 2nd box, and so on. I am using the acm.jar for this, <a href="http://jtf.acm.org/javadoc/student/index.html" rel="nofollow">http://jtf.acm.org/javadoc/student/index.html</a>. </p>

<pre><code>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);

        }




    }
}
</code></pre>

<p>I already figured out how to make the colors random, I cant figure out how I will substitute the boxes with the old ones. </p>

<p><strong>EDIT:::--------------------------------------------------------------------------------</strong></p>

<p>I did manage to get it working with the help of the guys below. Here is what the new for loop looks like:</p>

<pre><code>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&gt;maxBoxes)
                {
                    remove(getElement(0));
                }

                this.pause(100);

        }
</code></pre>

<p>One thing I dont understand is why the remove(getElement(0)) works,,  how does the element change its index once one is removed? If I have 10 elements 0-9, and I remove element(0) why does the other elements change its index? </p>
