Search code examples
javadoublebuffered

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.

  • 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


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