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);
}
}
}
Best Answer
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 aJPanel
. This also gives you a potential solution, becauseJPanel
has a methodsetDoubleBuffered(boolean)
, more specifically, this is implemented in theJComponent
class.I believe it would be sufficient to just replace
by
. Although I haven't tested this, I hope it helps you!
EDIT: Also, of course, when setting up your
frame
andcanvas
in themain
method, you'd have to place the method callsomewhere.