// GraphicAnimationOverABackground // modeled on code found at // http://www.dgp.toronto.edu/~mjmcguff/learn/java/07-backbuffer/ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AnimationOfAnImageOverABackgroundWithBackbuffer extends JApplet implements MouseMotionListener { private int width; private int height; private int mx; private int my; private Image backgroundImage; private Image spaceshipImage; private Image backbuffer; private Graphics backg; public void init() { width = getSize().width; height = getSize().height; mx = width/2; my = height/2; backgroundImage = getImage(getDocumentBase(), "background.gif"); spaceshipImage = getImage(getDocumentBase(), "spaceship.gif"); backbuffer = createImage(width, height); // backbuffer is an off-screen drawable image to be used for double-buffering backg = backbuffer.getGraphics(); // backg is a reference to the Graphics object property of the Image backbuffer & can now serve as a context for drawing an off-screen image (i.e. like the paint method's parameter g) addMouseMotionListener(this); } public void mouseMoved(MouseEvent e) { mx = e.getX(); my = e.getY(); backg.drawImage(backgroundImage, 0, 0, this); backg.drawImage(spaceshipImage, mx, my, this); repaint(); e.consume(); } public void mouseDragged(MouseEvent e) {} public void update(Graphics g) // must override the Component class's update method to prevent applet from being cleared (i.e. filled with the background color) { // otherwise, flickering will occur g.drawImage(backbuffer, 0, 0, this); } public void paint(Graphics g) { g.drawImage(backgroundImage, 0, 0, this); update(g); } }