This applet is an example of image animation. It does not wait for all the images to be loaded before starting the animation, that is why until all the images are loaded, you will see lots of flickering.

Let's look at the code, which can be found in ImageAnim.java:

Line 4 specifies the ImageAnim class as extending the Applet class and implementing the Runnable interface (see the HelloAnim applet for the explanation):

	public class ImageAnim extends Applet implements Runnable {

The ImageAnim class declares an array of images, the number of images. and a Thread object, called my_thread:

    	Image[] images;
    	int num_images = 4;
    	Thread my_thread = null;
The array of images will hold the images for the animation.

Initializing

The init() function first creates space for the array to hold num_images by using the new command. It then initializes every entry in the array to hold an image:
    	public void init() {
		images = new Image[num_images];

		for (int i=0; i<num_images; i++) {
			images[i] = getImage(getCodeBase(), "./images/ANIM" + i + ".GIF");
		}
      	}
In Java, you can concatenate strings with the + sign. So the applet looks for images that are called ANIM0.GIF, ANIM1.GIF, ....

The Thread

The applet's start function gets called after the init() function ends. The new operator is used to create a Thread object. By passing the this value, you ensure that this applet's run function gets called by the thread's start function:
    	public void start() {
        	my_thread = new Thread(this);
        	my_thread.start();
      	}
Once the thread is started, the real work gets done in the run function. An endless loop is started, which continuously loops through the pictures and draws them with the drawImage function. In between displaying images, the thread sleeps for 600 milliseconds. If the sleep is interrupted, it throws an exception of type InterruptedException:
    	public void run() {
        	while(true) {
			for (int i=0; i<num_images; i++) {
	    			getGraphics().drawImage(images[i], 0, 0, this);

            			try {
                			Thread.sleep(600);
              			}
            			catch(InterruptedException e) {
              			}
			}
        	}
        }


Back to Lecture2