import java.awt.*; import java.applet.Applet; /* * This applet moves one image in front of a background image. It * eliminates flashing by double buffering. */ public class MovingImage extends Applet implements Runnable { int frameNumber; int delay; Thread animatorThread; Dimension offDimension; Image offImage; Graphics offGraphics; Image stars; Image pizza; public void init() { String str; // How many milliseconds between frames? str = getParameter("fps"); int fps = (str != null) ? Integer.parseInt(str) : 10; delay = (fps > 0) ? (1000 / fps) : 100; stars = getImage(getDocumentBase(), "images/starfield.gif"); pizza = getImage(getDocumentBase(), "images/pizza.gif"); } public void start() { if (animatorThread == null) { animatorThread = new Thread(this); animatorThread.start(); } } public void stop() { animatorThread = null; offImage = null; offGraphics = null; } public boolean mouseDown(Event e, int x, int y) { if (animatorThread == null) { start(); } else { animatorThread = null; } return false; } public void run() { // Remember the starting time long startTime = System.currentTimeMillis(); while (Thread.currentThread() == animatorThread) { // Display the next frame of animation. repaint(); // Delay depending on how far we are behind. try { startTime += delay; Thread.sleep(Math.max(0, startTime-System.currentTimeMillis())); } catch (InterruptedException e) { break; } frameNumber++; } } // Paint the previous frame (if any). public void paint(Graphics g) { if (offImage != null) { g.drawImage(offImage, 0, 0, this); } } public void update(Graphics g) { Dimension d = size(); // Create the offscreen graphics context, if no good one exists. if ( (offGraphics == null) || (d.width != offDimension.width) || (d.height != offDimension.height) ) { offDimension = d; offImage = createImage(d.width, d.height); offGraphics = offImage.getGraphics(); } // Erase the previous image. offGraphics.setColor(getBackground()); offGraphics.fillRect(0, 0, d.width, d.height); offGraphics.setColor(Color.black); //Paint the frame into the image. paintFrame(offGraphics); // Paint the image onto the screen. g.drawImage(offImage, 0, 0, this); } void paintFrame(Graphics g) { Dimension d = size(); int w = stars.getWidth(this); int h = stars.getHeight(this); // If we've loaded any of the background image, draw it. if ((w > 0) && (h > 0)) { g.drawImage(stars, (d.width - w)/2, (d.height - h)/2, this); } w = pizza.getWidth(this); h = pizza.getHeight(this); // If we've loaded any of the moving image, draw it. if ((w > 0) && (h > 0)) { g.drawImage(pizza, ((frameNumber*5) % (w + d.width)) - w, (d.height - h)/2, this); } } }