// Shows .gif files one after another to create an animation. import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import javax.swing.*; public class LogoAnimator extends JPanel implements ActionListener { protected ImageIcon images[]; // array of animation frames protected int totalImages = 30, currentImage = 0, animationDelay = 50; // 50 millisecond delay protected String imageName = "images/deitel"; protected Timer animationTimer; // Default, no argument constructor public LogoAnimator() { setSize( getPreferredSize() ); images = new ImageIcon[ totalImages ]; URL url; for ( int i = 0; i < images.length; ++i ) { // Append image number to the name and load image url = getClass().getResource( imageName + i + ".gif" ); images[ i ] = new ImageIcon( url ); } } // Constructor with arguments public LogoAnimator( int num, int delay, String name ) { this(); totalImages = num; animationDelay = delay; imageName = name; } public void paintComponent( Graphics g ) { super.paintComponent( g ); images[ currentImage ].paintIcon( this, g, 0, 0 ); currentImage = ( currentImage + 1 ) % totalImages; } public void actionPerformed( ActionEvent e ) { repaint(); } public void startAnimation() { if ( animationTimer == null ) { currentImage = 0; animationTimer = new Timer( animationDelay, this ); animationTimer.start(); } else // continue from last image displayed if ( ! animationTimer.isRunning() ) animationTimer.restart(); } public void stopAnimation() { animationTimer.stop(); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getPreferredSize() { return new Dimension( 160, 80 ); } public static void main( String args[] ) { LogoAnimator anim = new LogoAnimator(); JFrame app = new JFrame( "Animator test" ); app.getContentPane().add( anim, BorderLayout.CENTER ); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); app.setSize( anim.getPreferredSize().width + 10, anim.getPreferredSize().height + 30 ); app.show(); } } /************************************************************************** * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall. * * All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/