Implementing Double Buffering in Java

Viewed 8363

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);
        }
    }
}
1 Answers
Related