| Animation by Example: Using Images
instead of Drawings by David Matuszek |
There's good news and bad news about using images in your program.
The good news is, it's just as easy to draw images as it is to draw simple shapes (like a ball). In this example, I have replaced the lines
g.setColor(Color.red); g.fillOval(model.xPosition, model.yPosition, model.BALL_SIZE, model.BALL_SIZE);
with
g.drawImage(controller.skull, model.xPosition, model.yPosition, null);
The bad news is:
The next page will talk about finding images. For now, let's look at the code for loading the images into memory.
/**
* Loads in the images we will use in this animation. There is an easier
* way to do this in Java 2, but this method also works with any Java.
*/
void loadImages() {
// Create a MediaTracker to wait for the images to be loaded
MediaTracker tracker = new MediaTracker(this);
// Declare variables for the URLs
URL appletLocation = getCodeBase();
URL imageURL = null;
try {
// Start loading the graveyard image
imageURL = new URL(appletLocation + "/images/boothill-blue.jpg");
graveyard = getImage(imageURL);
tracker.addImage(graveyard, 0);
// Start loading the skull image
imageURL = new URL(appletLocation + "/images/skull-1.gif");
skull = getImage(imageURL);
tracker.addImage(skull, 0);
}
catch (MalformedURLException e) { e.printStackTrace(); }
// Wait for the images to be loaded; does no error checking
try { tracker.waitForAll(5000); }
catch (InterruptedException e) {}
}
You need to specify a URL (not just a file) from which to load an image. Do
this by finding out the URL of the applet with Applet.getCodeBase(),
then adding the name of your file to it, and making a new URL with the resultant
String.
Next you start loading the image with getImage(imageURL).
Since this might take a long time, the method asks for the image and returns
immediately, before the image has actually been gotten.
Next you tell a "MediaTracker" to watch the images being loaded,
with MediaTracker.addImage(image, group). Fortunately, you don't
need a separate MediaTracker for each image; you can watch them all at once,
by just putting them all in the same group number.
Finally, tell the MediaTracker to waitForAll(milliseconds) images,
or give up if it doesn't get them in the specified number of milliseconds (5000
is five seconds). The above code does not check that the images loaded successfully;
I should fix that, but I'll leave it as "an exercise for the student."
Credits:
![]() |
|
|
|
|