Java Code
/* Demonstrate loops with animation
* @author: E.S.Boese
* @version : Fall 2005
*/
import java.awt.*;
import javax.swing.*;
public class AnimateThreads extends JApplet implements
Runnable
{
int x, y, size, move, speed, count;
Thread thread;
public void init( )
{
x = 0;
y = 50;
size = 20; // width and height same
move = 2; //num pixels to move each time thru loop
count = 0;
thread = new Thread(this);
thread.start( );
}
public void run( )
{
try
{
while( true )
{
repaint( );
thread.sleep( 50 );
// slow down painting so we can see it
}
}catch( Exception e )
{
}
}
public void paint ( Graphics g )
{
g.clearRect ( 0,0,300,300); // 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
if ( x < 0 )
move = -move;
}
}
©2007 by E.S.Boese. All Rights Reserved