[英]Implementing Double Buffering in Java
I have a simple Java JFrame canvas. 我有一个简单的Java JFrame画布。 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.
我想实现双缓冲以消除闪烁,但我对Java很新,并且不熟悉如何这样做。 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);
}
}
}
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). 首先,你应该避免混合重型和轻量级组件(AWT和SWING),主要是因为它们使用非常不同的绘图方法(如果你想了解更多,请阅读此处 )。
So instead of the Canvas
, you could use a JPanel
. 因此,您可以使用
JPanel
代替Canvas
。 This also gives you a potential solution, because JPanel
has a method setDoubleBuffered(boolean)
, more specifically, this is implemented in the JComponent
class. 这也为您提供了一个潜在的解决方案,因为
JPanel
有一个方法setDoubleBuffered(boolean)
,更具体地说,这是在JComponent
类中实现的。
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 编辑:当然,当在
main
方法中设置frame
和canvas
时,您必须放置方法调用
canvas.setDoubleBuffered(true);
somewhere. 某处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.