Double Buffering: slick graphics


Double buffering is a technique that reduces nasty flicker when you repaint your graphics. Simply put, it draws everything to an off-screen buffer, and then exchanges it with the on-screen buffer.


Double buffering in Java is easy: just drop in code!

Needed items:

This is all you need to add:
public class mySuperCoolPanel extends Panel {
  ...    // other stuff

  // double buffering
  Dimension offScreenSize = null;
  Graphics offScreenGraphics = null;
  Image offScreenImage = null;

  ...    // other stuff

  public final synchronized void update (Graphics g) {
    Dimension d = size();
    if ((offScreenImage == null) || (d.width != offScreenSize.width) ||
	(d.height != offScreenSize.height)) {
      offScreenImage = createImage(d.width, d.height);
      offScreenSize = d;
      offScreenGraphics = offScreenImage.getGraphics();
      offScreenGraphics.setFont(getFont());
    }
    paint(offScreenGraphics);
    g.drawImage(offScreenImage, 0, 0, this);
  }
}