New to Java? We'll help you get started with our revised beginner's tutorial, or our free online textbook.


Get the latest Java books
h t t p : / /w w w . j a v a c o f f e e b r e a k . c o m /

Java Coffee Break

Menu



Learning Java

Articles
Author Profiles
Lessons
FAQ's
Books
Newsletter
Tutorials
Talk Java!

Using Java

Applets
JavaBeans
Servlets
Resources
Discuss Java


Looking for Java resources? Check out the Java Coffee Break directory!

 Listing One

import java.applet.Applet;
import java.awt.*;

//
//
// MediaTrackerDemo
//
//
public class MediaTrackerDemo extends Applet implements Runnable
{
    Image[]      imgArray = null;
    MediaTracker tracker  = null;
    int			 current  = 0;
    Thread		 animThread=null;

    // Check for a mouse click, to start the images downloading
    public boolean mouseDown(Event  evt, int  x, int  y)
    {
        if (tracker == null)
        {
            // Create a new media tracker, to track loading images
            tracker = new MediaTracker(this);

            // Create an array of three images
            imgArray = new Image[3];

            // Start downloading the images
            for (int index=0; index < 3; index++)
            {
                // Load the image
                imgArray[index] = getImage( getDocumentBase(),
                     "anim" + (index+1) + ".gif"); 

                // Register it with media tracker
                tracker.addImage(imgArray[index], index);
            }

            // Start animation thread
            animThread = new Thread(this);
            animThread.start();
        }

        return true;
    }

    public void update(Graphics g) {
        // Don't repaint gray background
        paint(g);
    }

    public void paint (Graphics g)
    {
        g.setColor(Color.white);
        g.fillRect(0,0, 200, 200);
        g.setColor(Color.black);

        // Check to see if images have started loading
        if (tracker == null)
        {
            g.drawString ("Click to start loading",20,20);
        }
        else
        // Check to see if images have loaded
        if (tracker.checkAll())
        {
            g.drawImage(imgArray[current++], 0, 0, this);

            if (current >= imgArray.length) current=0;
        }
        else
        // Still loading
        {
            g.drawString ("Images are loading...", 20,20);
        }
    }

    public void run()
    {
        try
        {
            tracker.waitForAll();

            for (;;)
            {
                // Repaint the images
                repaint();

                Thread.sleep(2000);
            }								
        }
        catch (InterruptedException ie)	{};
    }
}

Back

Back to main


Copyright 1998, 1999, 2000 David Reilly

Privacy | Legal | Linking | Advertise!

Last updated: Monday, June 05, 2006