Make your own animation from a series of images : Animation « 2D Graphics GUI « Java

Make your own animation from a series of images


import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Main extends JPanel implements ActionListener {
  ImageIcon images[];
  int totalImages = 30, currentImage = 0, animationDelay = 50;
  Timer animationTimer;
  public Main() {
    images = new ImageIcon[totalImages];
    for (int i = 0; i < images.length; ++i)
      images[i] = new ImageIcon("images/java" + i + ".gif");

  public void paintComponent(Graphics g) {
    if (images[currentImage].getImageLoadStatus() == MediaTracker.COMPLETE) {
      images[currentImage].paintIcon(this, g, 0, 0);
      currentImage = (currentImage + 1) % totalImages;

  public void actionPerformed(ActionEvent e) {

  public void startAnimation() {
    if (animationTimer == null) {
      currentImage = 0;
      animationTimer = new Timer(animationDelay, this);
    } else if (!animationTimer.isRunning())

  public void stopAnimation() {
  public static void main(String args[]) {
    Main anim = new Main();
    JFrame app = new JFrame("Animator test");
    app.add(anim, BorderLayout.CENTER);
    app.setSize(anim.getPreferredSize().width + 10, anim.getPreferredSize().height + 30);


Related examples in the same category

1.Is Event Dispatcher ThreadIs Event Dispatcher Thread
2.Timer based animation
3.A rotating and scaling rectangle.
4.Fade out an image: image gradually get more transparent until it is completely invisible.
5.Font size animation
6.Hypnosis animationHypnosis animation
7.Noise ImageNoise Image
8.How to create Animation: Paint and threadHow to create Animation: Paint and thread
9.How to create animationHow to create animation
10.Animation: bounce
11.Image BouncerImage Bouncer
12.Text animationText animation
13.Buffered Animation DemoBuffered Animation Demo
14.Bouncing CircleBouncing Circle
15.Hypnosis SpiralHypnosis Spiral
16.Animator DemoAnimator Demo
17.Towers of Hanoi
18.Composition technique in this animation.
19.Animated Button
20.Animated Message Panel
21.Animated PasswordField
22.Animated TextField
23.A simple spring simulation in one dimension
24.Shows an animated bouncing ball
25.Shows animated bouncing ballsShows animated bouncing balls