Java Reference
In-Depth Information
you've read the entire file. Thus, when getImage() returns, the Image object is created, but
its size is set to -1, -1. Because two threads are now running (see Chapter 22 ) , two outcomes
are possible. Either the image-reading thread reads enough to know the width and height be-
fore you need them, or you need them before the thread reads enough to know them. The
curious-looking code in paint() is defensive about this. You should be, too.
But what if you really need the size of the image, for example to lay out a larger panel? If
you read a bit of the Image documentation, you might think you can use the pre-
pareImage() method to ensure that the object has been loaded. Unfortunately, this method
can get you stuck in a loop if the image file is missing because prepareImage() never re-
turns true! If you need to be sure, you must construct a MediaTracker object to ensure that
the image has been loaded successfully. That looks something like this:
/**
* This CODE FRAGMENT shows using a MediaTracker to ensure
* that an Image has been loaded successfully, then obtaining
* its Width and Height. The MediaTracker can track an arbitrary
* number of Images; the "0" is an arbitrary number used to track
* this particular image.
*/
Image im;
int imWidth, imHeight;
public void setImage(Image i) {
im = i;
MediaTracker mt = new MediaTracker(this);
// use of "this" assumes we're in a Component subclass.
mt.addImage(im, 0);
try {
mt.waitForID(0);
} catch(InterruptedException e) {
throw new IllegalArgumentException(
"InterruptedException while loading Image");
}
if (mt.isErrorID(0)) {
throw new IllegalArgumentException(
"Couldn't load image");
}
imWidth = im.getWidth(this);
imHeight = im.getHeight(this);
}
Search WWH ::




Custom Search