Programming Tutorials

'double buffering' Sample program in J2ME

By: Charles in J2ME Tutorials on 2007-09-17  

Double buffering is a technique used to avoid flickering when rendering graphics in J2ME applications. The basic idea is to create an off-screen image and draw everything to that image, and then draw the final image to the screen. This way, the final image appears all at once and there is no flicker caused by the screen being partially updated.

Here's a sample program that demonstrates double buffering in J2ME:

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;

public class DoubleBufferingDemo extends MIDlet {
    private Display display;
    private MyCanvas canvas;

    public void startApp() {
        display = Display.getDisplay(this);
        canvas = new MyCanvas();

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

    private class MyCanvas extends Canvas {
        private int x = 0;
        private int y = 0;

        public void paint(Graphics g) {
            // Create an off-screen image and graphics context
            int w = getWidth();
            int h = getHeight();
            int[] buf = new int[w * h];
            Graphics offscreen = Graphics.createImageGraphics(buf, w, h);

            // Draw everything to the off-screen graphics context
            offscreen.fillRect(0, 0, w, h);
            offscreen.drawLine(0, 0, x, y);

            // Draw the final image to the screen
            g.drawRGB(buf, 0, w, 0, 0, w, h, true);

        public void keyPressed(int keyCode) {
            // Move the line based on user input
            switch (getGameAction(keyCode)) {
                case LEFT:
                case RIGHT:
                case UP:
                case DOWN:

            // Repaint the canvas

This program creates a custom Canvas that uses double buffering to draw a line on the screen that can be moved using the arrow keys. The paint() method creates an off-screen image using an integer buffer, draws the line to the off-screen graphics context, and then draws the final image to the screen. The keyPressed() method updates the position of the line and then repaints the canvas to show the new position.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in J2ME )

Latest Articles (in J2ME)