// BunsenAnimatorPanel.java
// JPanel dedicated to drawing and animating the beard
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BunsenAnimatorPanel extends JPanel implements ActionListener {
protected ImageIcon beard[ ];
protected int currentImage = 0; // subscript of the current image
protected int totImages = 24; // total number of images
protected int delay = 40; // 40 millisecond delay between events
protected Timer animationTimer;
public BunsenAnimatorPanel( ) {
// load the images when the applet begins
beard = new ImageIcon[ totImages ]; // creates the array
for ( int i = 0; i < beard.length; i++ )
beard[ i ] = new ImageIcon( "images/bunsen" + i + ".jpg" );
startAnimation( );
}
public void actionPerformed( ActionEvent e ) {
repaint( );
}
public void startAnimation( ) {
if ( animationTimer == null ) {
currentImage = 0;
animationTimer = new Timer( delay, this );
animationTimer.start( );
}
else
if ( !animationTimer.isRunning( ) )
animationTimer.restart( );
}
public void stopAnimation( ) {
animationTimer.stop( );
}
public void paintComponent( Graphics g ) {
super.paintComponent( g );
if ( beard[ currentImage ].getImageLoadStatus( ) == MediaTracker.COMPLETE ) {
beard[ currentImage ].paintIcon( this, g, 0, 0 );
currentImage = ++currentImage % totImages;
}
}
}