Implementing Double Buffering in Java

kaptaincooke picture kaptaincooke · Jul 26, 2012 · Viewed 8.1k times · Source

I have a simple Java JFrame canvas. I am updating what is on the screen every half second or so, and have flickering. I want to implement double buffering to eliminate the flickering, but I am fairly new to Java and am unfamiliar with how to do so. I have found some examples, but not sure how to implement their methods into mine.

Below is the basic setup of how I have things now. This is not my exact code- just an example of the basic setup.

Thanks for any push in the right direction!

public class myCanvas extends Canvas{
    //variables
    Color rectColor=Color.red;

    public myCanvas()
    {
    }

    public void paint(Graphics graphics)
    {
        //initial setup, such as
        graphics.setColor(rectColor);
        graphics.fillRect(X,Y,W,H);
    }
    public static void main(String[] args)
    {
        myCanvas canvas = new myCanvas();
        JFrame frame = new JFrame("GUI");
        frame.setSize(frameWidth,frameHeight);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(canvas);
        frame.setVisible(true);
        while(true){
            rectColor=Color.green;
            canvas.validate();
            canvas.repaint();
            Thread.sleep(500);
        }
    }
}

Answer

Kierrow picture Kierrow · Jul 26, 2012

First of all, you should avoid mixing heavy- and lightweight components (AWT and SWING), mostly because they use very different methods of drawing to the display (read here if you want to know more).

So instead of the Canvas, you could use a JPanel. This also gives you a potential solution, because JPanel has a method setDoubleBuffered(boolean), more specifically, this is implemented in the JComponent class.

I believe it would be sufficient to just replace

public class myCanvas extends Canvas

by

public class myCanvas extends JPanel

. Although I haven't tested this, I hope it helps you!

EDIT: Also, of course, when setting up your frame and canvas in the main method, you'd have to place the method call

canvas.setDoubleBuffered(true);

somewhere.