This applet is an extension of our ImageAnim applet. It waits for all the images to be loaded before starting the animation, and also does error checking while the images are loaded.
Let's look at the code, which can be found in ImageTracker.java. We will only discuss the differences since the applets look alike:
The ImageTracker class, like the ImageAnim applet, declares an array of images, the number of images, and a Thread object, called my_thread. However, it also declares a Mediatracker object:
public class ImageTracker extends Applet implements Runnable { Image[] images; int num_images = 4; Thread my_thread = null; MediaTracker tracker;
The tracker object will trace the status of the images.
The init() function first creates space for the array to hold num_images by using the new command. It then creates the MediaTracker object. Then it gets all the images, and adds the them to the tracker object (so that we can wait until they hava all been loaded (in run()):
public void init() { images = new Image[num_images]; tracker = new MediaTracker(this); for (int i=0; i<num_images; i++) { images[i] = getImage(getCodeBase(), "./images/ANIM" + i + ".GIF"); tracker.addImage(images[i], i); } }
The applets' start functions are the same. Let's look at the differences in the run function. The function starts off by displaying a message in the statusbar of the browser: "Loading Images". Then it calls the MediaTracker.waitForAll() function to wait until all the images are loaded. The waitForALL function starts loading all images tracked by this media tracker. The method waits until all the images being tracked have finished loading. If there was an error while loading an image then that image is considered finished loading (you use the isErrorAny or isErrorID method to check for errors). So, then the applet calls the MediaTracker.isErrorAny() function to check if there were any errors while downloading any of the images. If there was an error, it displays an error message in the stusbar. If there were no errors, then "Done Loading Images" is displayed in the statusbar:
public void run() { showStatus("Loading Images); try { tracker.waitForAll(); } catch(InterruptedException e) { } if (tracker.isErrorAny()) { showStatus("Error loading images. See Ya!"); return; } showStatus("Done Loading Images");
When all images are loaded, we can do the drawing. Here, just like in the ImageAnim applet, 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:
while(true) { for (int i=0; i<num_images; i++) { getGraphics().drawImage(images[i], 0, 0, this); try { Thread.sleep(600); } catch(InterruptedException e) { } } }