9.5. Double Buffering

One important application of offscreen images is double buffering. This is a technique that eliminates flicker in animated graphics. Double buffering gets its name from the fact that there are two graphics areas (buffers) involved—the onscreen buffer and the offscreen image. Animation is just the process of showing one frame after another. Without double buffering, you simply clear the drawing area and draw the new frame. Repeated clearing and redrawing produces flicker, as shown in the next example, Annoyance. This class simply renders a filled rectangle at the coordinates of the last mouse motion event. When you move the mouse around in the window, you'll notice the flicker.

import java.awt.*;
import java.awt.event.*;

public class Annoyance
    extends ApplicationFrame
    implements MouseMotionListener {
  public static void main(String[] args) {
    new Annoyance();
  }

  private int mX, mY;
  public Annoyance() {
    super("Annoyance v1.0");
    addMouseMotionListener(this);
    setVisible(true);
  }
  
  public void mouseMoved(MouseEvent me) {
    mX = (int)me.getPoint().getX();
    mY = (int)me.getPoint().getY();
    repaint();
  }
  
  public void mouseDragged(MouseEvent me) { mouseMoved(me); }
  
  public void paint(Graphics g) {
    int s = 100;
    g.setColor(Color.blue);
    g.fillRect(mX - s / 2, mY - s / 2, s, s);
  }
}

Double buffering eliminates the flicker from this example. Basically, I'll render the rectangle into an offscreen image and then transfer the image to the screen. This erases the old picture and draws ...

Get Java 2D Graphics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.