Double buffering is a well-known technique for reducing flicker in drawing and animations. Imagine you are implementing an animation that clears and redraws the entire screen for each frame of the animation. Without double buffering, the animation will flicker badly as the screen is cleared and redrawn. With double buffering, the new frame is drawn into an off-screen image (the buffer). When the off-screen drawing is complete, the image is drawn on the screen in one smooth, quick move. You pay a price in the memory that’s needed for the off-screen image, but the improvement in the quality of the animation is dramatic.

We can find out whether a Canvas is double buffered by calling the isDoubleBuffered() method. If the j2ME implementation does not give us double buffering, we’ll have to do it ourself.

  • Create an off-screen image by calling the static Image.createImage(int width, int height) method.
  • Obtain a Graphics that draws into the image by calling getGraphics() on the Image.
  • In the paint() method of the Canvas, use drawImage() to put the off-screen image on the Canvas.
import javax.microedition.lcdui.*;

public class OffscreenCanvas
    extends Canvas {
  private Image mImage;
  public void paint(Graphics g) {
    if (mImage == null)
    g.drawImage(mImage, 0, 0, Graphics.TOP | Graphics.LEFT);

  private void initialize() {
    int w = getWidth();
    int h = getHeight();

    mImage = Image.createImage(w, h);

    Graphics g = mImage.getGraphics();

    g.drawRect(0, 0, w - 1, h - 1);
    g.drawLine(0, 0, w - 1, h - 1);
    g.drawLine(w - 1, 0, 0, h - 1);
This article is about: Code Sample, J2ME,


StackTips provides programming tutorials, how-to guides and code snippets on different programming languages. Follow us on Twitter


Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.