Java Code
/* Demonstrate loops with animation */
import java.awt.*;
import javax.swing.*;
public class AnimateImage extends JApplet
{
int x, y, size, move, speed, count;
Image walker;
public void init( )
{
walker = getImage( getCodeBase( ), "zil_walk_right.gif" );
}
public void paint ( Graphics g )
{
x = 0;
y = 50;
size = 25; // width and height same
move = 1; //number of pixels to move each time through loop
count = 0;
speed = 10000000; // slow down loop (hack way without threads)
while ( count < 5000 )
{
g.clearRect ( x, y, size, size); // erase space
x = x + move; // new x coordinate; y stays the same
g.drawImage ( walker, x, y, this );
// did we hit the edge of the applet?
if ( x + size > getWidth( ) )
{
move = -move; // if so, go back
walker = getImage( getCodeBase( ), "zil_walk_left.gif" );
}
for ( int i=0; i<speed; i++ ) // hack way to slow down without threads
; // slow down painting so we can see it
count = count + 1;
}
}
}
Back to Code Examples
©2006-
by E.S.Boese. All Rights Reserved