Java Reference
In-Depth Information
System.err.println("Couldn't load one or more sprite images");
System.exit(1);
}
}
// Get the sprite that corresponds to the size of the target
public Image getSpriteBySize(int size) {
// Set up an object to return
Image imageToReturn = null;
if (size == 25) { // Get the little black target
imageToReturn = smallTarget;
} else if (size == 40) { // Get the medium-sized blue target
imageToReturn = mediumTarget;
} else if (size == 50) { // Get the large green target
imageToReturn = largeTarget;
} else { // oops - no such target, so tell the player and stop
throw new IllegalArgumentException("Unknown Sprite Size: " + size);
System.exit(1);
}
return imageToReturn;
}
}
If you didn't skip straight to this chapter, then you've seen a very similar class in Chapter 7, “Writing
a User Interface,” when we examined the MineIcon class. That class creates a set of ImageIcon objects
rather than a set of Image objects and doesn't have an init method, but the idea is the same. We load a
set of images into a set of static variables.
An important implementation detail is that those variables being static: being static ensures that
each memory gets loaded into the memory only once. Imagine the memory consumption if every target
loaded its own separate image. We'd quickly have a problem, either with a crash because we ran out of
memory or with horrible performance because images are constantly loading. As it happens, the init
method gets called only once, so the images would get loaded into memory only once. However, the
static loading technique is still a good idea to keep around, just in case. There's an old joke (familiar to
members of the United States Navy) that goes: “I know I'm being paranoid, but am I being paranoid
enough?” It's often a good question for software developers, too.
Expanding the ShootingGallery Game
As I promised earlier, here's a collection of ideas for making the ShootingGallery game more complex
(and more like a game you'd actually want to play):
A button or menu item or keyboard command (use the KeyListener interface,
which works much like the MouseListener interface) that toggles between Start
and Stop
A Pause button or menu item or keyboard command
A New Game menu item or keyboard command
Search WWH ::




Custom Search