Monthly Archive for April, 2008

Simple Double Buffering in Java

I recently wrote a simple program that had a background image, with smaller, draggable images over top of it. It worked fine when both the images and background were in the same JPanel, but when I tried to paint them in a JApplet, the dragged objects started to flicker with each call to repaint().

What I found that I needed to do was have all of the objects painted offscreen, added to a temporary image, and then that image painted into the JApplet (double buffering). That is where using an auxiliary Graphics component comes in.

import java.awt.*;
import javax.swing.*;

public class SomeApplet extends JApplet {
  // ...
  private Graphics bufferGraphics; // graphics buffer
  private Image bufferImage; // temporary offscreen image

public void init() {
    // ...
    bufferImage = createImage(*WIDTH*, *HEIGHT*);
    bufferGraphics = bufferImage.getGraphics();
  }

public void paint(Graphics g) {
    bufferGraphics.drawImage(*IMAGE 1*, x, y, null);
    bufferGraphics.drawImage(*IMAGE 2*, x, y, null);
    // ...
    g.drawImage(bufferImage,0,0,null);
  }
}

The key is to paint all of your images using the extra Graphics component, and then paint the temporary image associated with that component using the paint() method’s Graphics component. This way, the whole image is drawn to the canvas only once for each repaint() called.

I’m no Java guru, but I had to do a bit of searching around before figuring out a simple way to do this. A lot of tutorials included extra code which made understanding it difficult. If you find this helpful, let me know by leaving a comment.