May 2000
Beginner
726 pages
21h 42m
English
java.awt.MediaTracker
is a utility class that simplifies life if we have to wait for one or
more images to be loaded before they’re displayed. A
MediaTracker monitors the preparation of an image
or a group of images and lets us check on them periodically, or wait
until they are completed. MediaTracker uses the
ImageObserver interface internally to receive
image updates.
The following
applet, TrackImage,
uses a MediaTracker to wait while an image is
prepared. It shows a "Loading . . .”
message while it’s waiting. (If you are retrieving the image
from a local disk or very fast network, this message might go by
quickly, so pay attention.)
//file: TrackImage.java import java.awt.*; public class TrackImage extends javax.swing.JApplet implements Runnable { final int MAIN_IMAGE = 0; Image image; MediaTracker tracker; boolean loaded = false; Thread thread = null; String message = "Loading..."; public void init( ) { image = getImage(getClass( ).getResource(getParameter("image"))); tracker = new MediaTracker(this); tracker.addImage(image, MAIN_IMAGE); } public void start( ) { if (!tracker.checkID(MAIN_IMAGE)) { thread = new Thread(this); thread.start( ); } } public void stop( ) { thread.interrupt( ); thread = null; } public void run( ) { repaint( ); try { tracker.waitForID(MAIN_IMAGE); } catch(InterruptedException e) {} if (tracker.isErrorID(MAIN_IMAGE)) message = "Error"; else loaded = true; repaint( ); } public void paint(Graphics g) { if (loaded) g.drawImage(image, ...Read now
Unlock full access