|
|
|
|||
|
Moving an Image Across the ScreenThis page features an example applet that moves one image (a rocketship) in front of a background image (a field of stars). You could implement this in one of two ways -- either using one label per image, or using one custom component that paints both images. Because this lesson features painting, this section features the custom component approach, as implemented inMovingImageTimer.java.
Below are the two images this applet uses. rocketship.gif: ![]() starfield.gif: ![]() This figure has been reduced to fit on the page. Click the image to view it at its natural size. Here's a picture of the applet's GUI. Remember that you can click on the applet to stop or start the animation. ![]() This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.
The code for performing this animation isn't complex.
Essentially, it's a copy of the animation template
that, instead of using a label to perform animation,
uses a custom component.
The custom component is a
You might think that this program
doesn't need to clear the background,
since it uses a background image.
However, clearing the background is still necessary.
One reason is that the applet usually starts painting before
the images are fully loaded.
If the rocketship image loaded before the background image,
you would see parts of multiple rocketship
until the background image loaded.
Another reason is that
if the applet painting area were wider than the background image,
for some reason,
then you'd see multiple rocketships to either side of the background image.
You could solve the first problem by delaying all painting until both images are fully loaded. The second problem could be solved by scaling the background image to fit the entire applet area. You'll learn how to wait for images to be fully loaded in Improving the Appearance and Performance of Image Animation, later in this lesson. Scaling is described in Displaying Images. | |||
|