Alfred
Alfred

Reputation: 1663

Double Buffering in Java

I found this code of double buffering on internet but it has no explaination. I am a little confused in this code.

Here is the code:

public void update(Graphics g)
{
    if(i==null)
    {
        i=createImage(getWidth(), getHeight());
        graph=i.getGraphics();
    }

    graph.setColor(getBackground());
    graph.fillRect(0, 0, getWidth(),getHeight());
    graph.setColor(getForeground());

    paint(graph);

    g.drawImage(i,0,0,this);
  }

Regards

Upvotes: 2

Views: 1096

Answers (2)

AbstractChaos
AbstractChaos

Reputation: 4211

The basic idea of Double Buffering is to create the image off screen then display it all at once.

Double Buffering

From the java tutorials found here

The code you have there first creates an image on first way through to be your "Back Buffer" with this bit, i is likely a field such as

 private Image i;
 private Graphics graph;

 if(i==null)
{
    i=createImage(getWidth(), getHeight());
    graph=i.getGraphics();
}

Then Paints the background color onto the image with this

graph.setColor(getBackground());
graph.fillRect(0, 0, getWidth(),getHeight());

Then sets the front ready for drawing.

graph.setColor(getForeground());
paint(graph); /draws

Finally drawing the back Buffer over to the primary surface.

g.drawImage(i,0,0,this);

Upvotes: 6

Daniel Earwicker
Daniel Earwicker

Reputation: 116654

The graphics operations are all performed on a Graphics obtained from i, which is a bitmap in memory.

When they're finished, the bitmap is drawn onto the "real" (screen) Graphics object g. So the user will never see half-finished drawing, which eliminates flicker.

The field i is allocated the first time and then reused, so it is not only used once.

Upvotes: 2

Related Questions