Return to article
Moving an Image Across the Screen: Example7Applet
The code below shows the important methods that we had
to update the images.
The code for the entire applet can be found in
Example7Applet.java.
Image world;
Image car;
/**
* Initialize the applet and compute the delay between frames.
*/
public void init() {
String str = getParameter("fps");
int fps = (str != null) ? Integer.parseInt(str) : 10;
delay = (fps > 0) ? (1000 / fps) : 100;
world = getImage(getCodeBase(), "world.gif");
car = getImage(getCodeBase(), "car.gif");
}
/**
* Paint the previous frame (if any).
*/
public void paint(Graphics g) {
update(g);
}
/**
* Paint a frame of animation.
*/
public void paintFrame(Graphics g) {
Dimension d = size();
int w = world.getWidth(this);
int h = world.getHeight(this);
if ((w > 0) && (h > 0)) {
//If we've loaded the world image, draw it.
g.drawImage(world, (d.width - w)/2, (d.height - h)/2, this);
}
w = car.getWidth(this);
h = car.getHeight(this);
if ((w > 0) && (h > 0)) {
//If we've loaded the car image...
w += d.width;
//draw car 1
g.drawImage(car, d.width - ((frame * 5) % w), (d.height - h)/3, this);
//draw car 2
g.drawImage(car, d.width - ((frame * 7) % w), (d.height - h)/2, this);
}
}