Java Code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TimerEx extends JApplet implements ActionListener
{
Image img;
ImageIcon icon;
int x, y, moveX, moveY;
Timer timer;
int DELAY = 20;
public void init( )
{
x=5; y=5;
moveX = 10;
moveY = 5;
img = getImage( getCodeBase( ), "View.png" );
timer = new Timer( DELAY, this );
timer.start( );
}
public void paint ( Graphics g )
{ // clearRect clears a small portion of the screen to prevent flicker
g.clearRect( x, y, img.getWidth(this), img.getHeight(this) );
x = x + moveX;
y = y + moveY;
g.drawImage( img, x, y, this );
}
public void actionPerformed( ActionEvent ae )
{
if ( x <= 0 || x >= this.getWidth( ) - img.getWidth(this) )
moveX = moveX * -1;
if ( y <= 0 || y >= this.getHeight( ) - img.getHeight(this) )
moveY = moveY * -1;
repaint( ); // force a call to the paint method
}
}
©2006 by E.S.Boese. All Rights Reserved