Question

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

  • Why is the Image "i" used? What is its use if it is to be used once?

  • Why are we assigning changing color to Foreground color,when we already have set color?

  • What is g.drawImage() method doing?

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

Was it helpful?

Solution

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);

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top