In this tutorial we will create a double buffer in Java and then test it by animating a bouncing ball, like the example above. So what exactly is a double buffer? When displaying images on the screen in Java, be it an animation or game, writing each image to the screen, one after the other, produces two undesirable effects know as "flicker" and "page tearing". With a double buffer, each image is first drawn on an invisible back buffer, and then the back buffer is drawn to the screen each frame. This allows all images to be drawn to the screen at once and eliminates flicker, for the most part.

import java.applet.*;
import java.awt.*;
public class DBuffer extends Applet{
    public static final int WIDTH = 250;
    public static final int HEIGHT = 250;
    Graphics backBuffer;
    Image frontBuffer;
    Image background;
    Image ball;
    int ballX = 36;
    int ballY = 50;
    int ballSpeedX = 5;
    int ballSpeedY = 10;
    int ballWidth = 50;
    Dimension appletSize;
    public void init(){
        this.setSize(WIDTH, HEIGHT);
        appletSize = getSize();
        frontBuffer = createImage(appletSize.width,appletSize.height);
        backBuffer = frontBuffer.getGraphics();
        background = getImage(getDocumentBase(), "wood.png");
        ball = getImage(getDocumentBase(),"ball.png");
        Thread t = new Thread(new MainLoop());
        t.start();
    }
    public class MainLoop implements Runnable{
        public MainLoop(){
        }
        public void run(){
            while(true){
                ballX+=ballSpeedX;
                ballY+=ballSpeedY;
                if(ballX < 0 || ballX > 250-ballWidth){
                    ballSpeedX = -ballSpeedX;
                }
                if(ballY < 0 || ballY > 250-ballWidth){
                    ballSpeedY = -ballSpeedY;
                }
                repaint();
                try {
                    Thread.sleep(20);
                }
                catch (InterruptedException ex){
                }
            }
        }
    }
    public void drawScreen(Graphics display){
        backBuffer.drawImage(background,0,0,null);
        backBuffer.drawImage(ball, ballX, ballY, null);
        backBuffer.drawString("Nice and Smooth",0,240);
        display.drawImage(frontBuffer,0,0,this);
    }
    public void update(Graphics display){
        drawScreen(display);
    }
} 

We created a thread called MainLoop that sleeps for 20 milliseconds every frame giving us a steady frame rate. Each iteration of the MainLoop thread calls the repaint() method of the Applet class, which automatically calls the update() method. The update method calls our own drawScreen method where the double buffer is put to work.