Java Code

/* Demonstrate loops with animation
 * @author: E.S.Boese
 * @version : Fall 2005
 */
import java.awt.*;
import javax.swing.*;
public class Animate extends JApplet
{
    int x, y, size, move, speed, count;
    public void paint ( Graphics g )
    {
        x = 0;
        y = 50;
        size = 20;	// width and height same
        move = 1; //num pixels to move each time thru loop
        count = 0;
        speed = 10000000;  // slow down loop

        while ( count < 5000 )
        {
            g.clearRect ( x, y, size, size);  // erase space
            x = x + move;   // new x coodinate, y stays same
            g.fillRect ( x, y, size, size ); 

                                 // did we hit the edge of the applet?
            if ( x + size > getWidth( ) )  
                move = -move;	// if so, go back
             for ( int i=0; i<speed; i++ ) 
				   ;  // slow down painting so we can see it

            count = count + 1;
        }
    }
}

Back to Code Examples
©2006- by E.S.Boese. All Rights Reserved