JFrame 中的 BufferStrategy 与 DIY 双缓冲

2022-01-24 00:00:00 java jframe doublebuffered

到目前为止,我已经通过创建和 Image 完成了双缓冲,使用其关联的 Graphics 对象将我想要的内容绘制到该 Image 上,然后使用 paint 方法的 Graphics 对象将该 Image 绘制到屏幕上.最近,我了解了 BufferStrategy 类及其用途.我想知道这两种方法的优缺点是什么.

我不认为我的问题很清楚.我想知道 DIY 方法和 BufferStrategy 的优缺点,以及何时应该使用其中一种.

解决方案

我一直使用默认的 BufferStrategy 得到很好的结果,但要小心

  • 始终在 EDT 上构建 GUI 组件
  • 切勿从除 EDT 之外的线程中绘图

这个优秀的例子 必须 双缓冲,因为它在初始线程而不是 EDT.相比之下,这个相当繁忙的 示例 仅依赖于 repaint() 调用以响应 Swing Timer.除了 composite,我很少需要屏幕外缓冲区.最后,这篇教程文章提供了更多指导.p>

Until now, I've done double buffering by creating and Image, drawing what I wanted to that Image using its associated Graphics object then draw that Image to the screen using the paint method's Graphics object. Recently, I learned about the BufferStrategy class and its uses. I was wondering what are the pros and cons of the two methods.

EDIT: I dont't think I made my question very clear. I wanted to know the pros/cons of both the DIY method and the BufferStrategy and when, if ever, I should use one or the other.

解决方案

I've always had good results using the default BufferStrategy by being careful to

  • Always construct GUI components on the EDT
  • Never draw from a thread except the EDT

This excellent example must double buffer because it draws continually on the initial thread rather than the EDT. In contrast, this fairly busy example relies on nothing more than repaint() called in response to a Swing Timer. I rarely need an offscreen buffer except for a composite. Finally, this tutorial article offers more guidelines.

相关文章