Return to article

Using MediaTracker to Avoid Incremental Display: Example9Applet


The code below shows the important methods that we had to update to use a MediaTracker instance to help load images. The animation isn't started until all the frames have been loaded. The code for the entire applet can be found in Example9Applet.java.

    MediaTracker tracker;
    Image frames[];

    /**
     * Initialize the applet and compute the delay between frames.
     */
    public void init() {
	String str = getParameter("fps");
	int fps = (str != null) ? Integer.parseInt(str) : 10;
	delay = (fps > 0) ? (1000 / fps) : 100;

	tracker = new MediaTracker(this);
	frames = new Image[10];
	for (int i = 1 ; i <= 10 ; i++) {
	    frames[i-1] = getImage(getCodeBase(), "duke/T" + i + ".gif");
	    tracker.addImage(frames[i-1], 0);
	}
    }

    /**
     * Paint a frame of animation.
     */
    public void paintFrame(Graphics g) {
	// Only paint when all images have arrived
	if (tracker.statusID(0, true) == MediaTracker.COMPLETE) {
	    g.drawImage(frames[frame % 10], 0, 0, null);
	}
    }