My application/applet loads images, but they aren't drawn to the screen. What's going on?


I've encountered this problem a few times in my own applications. When you load an image (using java.awt.Toolkit.getImage), the function returns immediately, and the image is loaded asynchronously. This means that sometimes an image isn't ready to be drawn, because it hasn't yet loaded. Depending on when the image is loaded, and when it is drawn, the problem can be intermittent and hard to track down.

If your application or applet MUST display the image, you can have it wait until the image is fully loaded. An animation applet, for example, may not have any useful work to do until the image(s) are loaded. To wait for images, you need to use the java.awt.MediaTracker class.

MediaTracker allows you to register an image with the tracker, and have your application or applet wait until the image is ready. Note that this isn't limited just to applets loading images over a network - from my own experience an application it can happen loading a small (<100 bytes) image from a local filesystem.

To register an image, you assign it an image number, and call the addImage method. Then you can call the waitFor(int) or waitForAll() methods.

// Pass media tracker any component (such as a canvas or an applet)
MediaTracker tracker = new MediaTracker( this );

// Add images
tracker.addImage ( myImage1, 0);
tracker.addImage ( myImage1, 1);
// Wait for images
try {
} catch (InterruptedException ie) {}

Once you start the wait, your application will block until the image has loaded. Then, you can call java.awt.Graphics.drawImage to display the image to your applet or application.