Learning Java
Custom Search

Previous Next

Animation

The Java Thread class is very useful for creating animation. The animation can run in its own thread while the main thread of the program does other things including listening for a termination request.

In our example, AnimationTest.java, we have a series of 9 images with the word Animation on them in various positions. It's nothing fancy, just a way of showing movement.

In our example, we have 2 classes, AnimationTest and TestAnPanel. The JFrame class AnimationTest will instantiate the JPanel TestAnPanel. TestAnPanel is our Runnable class and contains the instructions for the animation in its run method.

The 9 image files are

    images/Animation11.gif
    images/Animation12.gif
    .....
    images/Animation19.gif

We will load them into the array imageSet[9]. We will use the Toolkit class to load the images into our array before we create and start our thread.

When the thread is started, our run method is executed. In it we use modulus (%) to help us to loop thru the indexes of the array (from 0 to 9). Remember that modulus tells us what the remainder is after dividing the number by 9, in this case.

    currImage = (currImage + 1) % 9;

In our paint method, we take the current background color and fill the rectangle with it. Then we draw the current image as defined by the index currImage.

import java.awt.*;
import javax.swing.*;
import java.util.*;

public class AnimationTest extends JFrame {

    TestAnPanel taPanel = new TestAnPanel();

    public AnimationTest() {
	super("Animation Tester");
	setSize(450, 150);
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	add(taPanel);
	setVisible(true);
    }

    public static void main(String[] arguments) {
	AnimationTest test = new AnimationTest();
    }
}

class TestAnPanel extends JPanel implements Runnable {
    Thread myThread;

    Image imageSet[];
    int currImage=0;
    int numOfImages = 9;
	
    String imageFileName;

    TestAnPanel() {
	imageSet = new Image[numOfImages];
	setBackground(Color.red);
	Toolkit kit = Toolkit.getDefaultToolkit();

	// load images
	for (int i=0; i<numOfImages; i++) { 
	    imageFileName = "images/Animation" + (i+11) + ".gif";
	    imageSet[i] = kit.getImage(imageFileName);
	}

	myThread = new Thread(this);
	myThread.start();
    }

    public void run() {
	while (myThread != null) {
	    repaint();
	    currImage = (currImage + 1) % numOfImages;
	    try {
		myThread.sleep(400);
	    } catch (InterruptedException e) {
		System.out.println(myThread.toString() + 
					" interrupted.");
		return;
	    }
	}
    }

    public void paintComponent(Graphics g) {
	g.setColor(getBackground());
	g.fillRect(0, 0, getSize().width, getSize().height);
	g.drawImage(imageSet[currImage], 0, 0, this);
    }
}

Previous Next

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved