-1

I wanted to use double buffering for my code and I found this in the internet. But I dont understand how it works.

private Image doubleBuffer;

public void update(Graphics g) {
    Dimension size = getSize();
    if (doubleBuffer == null || doubleBuffer.getWidth(this) != size.width || doubleBuffer.getHeight(this) != size.height){
        doubleBuffer = createImage(size.width, size.height);
    }
    if (doubleBuffer != null) {
        Graphics g2 = doubleBuffer.getGraphics();
        paint(g2);
        g2.dispose();
        g.drawImage(doubleBuffer, 0, 0, null);
    }
    else {
        paint(g);
    }
thixuni
  • 11
  • 2

1 Answers1

1

The double buffer technique works in such way that you render/draw all graphics to an offscreen buffer (offscreen image), often called a backbuffer. Once all rendering/drawing is complete, the backbuffer is drawn/copied to the screen buffer.

The code starts with getting the dimensions of what is presumably the screen or window. Then the code checks if the doublebuffer (e.g. the backbuffer) exists, or if the backbuffer's width and height (dimensions) differ from the screen buffer (for example if user has resize its window or changed screen resolution). If the doublebuffer (backbuffer) does not exist or the dimensions are different, a new buffer is created with the same dimensions as the screen.

The code checks if the creation was successful (or that the doublebuffer exists), gets the graphics context of the buffer, calls paint() (where presumably all rendering is done) with the backbuffers graphics context, and then copy the backbuffer to the screen.

If, for some reason, the code was unable to create the buffer, the paint() method is called with the graphics context to the screen (I assume the variable g contains the graphics context to the screen), and rendering is done directly to this graphics context (e.g. to the screen).

I hope this helps.

Good luck with your game.

Eirik Moseng
  • 146
  • 5