是否可以在不使用EDT的情况下在Java Swing中执行活动渲染?

时间:2009-12-27 18:54:05

标签: java swing animation event-dispatch-thread

我正在研究使用Buffer Strategy以及Javadoc上描述的以下技术:

// Main loop
while (!done) {
 // Prepare for rendering the next frame
 // ...

 // Render single frame
 do {
     // The following loop ensures that the contents of the drawing buffer
     // are consistent in case the underlying surface was recreated
     do {
         // Get a new graphics context every time through the loop
         // to make sure the strategy is validated
         Graphics graphics = strategy.getDrawGraphics();

         // Render to graphics
         // ...

         // Dispose the graphics
         graphics.dispose();

         // Repeat the rendering if the drawing buffer contents 
         // were restored
     } while (strategy.contentsRestored());

     // Display the buffer
     strategy.show();

     // Repeat the rendering if the drawing buffer was lost
 } while (strategy.contentsLost());

}

执行动画时,最好避免EDTinvokeLaterinvokeAndWait

我的问题:

  • 如果这是在Swing应用程序中,我们不需要担心在EDT上拨打show吗?
  • 其他人可以在Swing应用中看到任何问题吗?

这受到interesting answer游戏编程的启发。

2 个答案:

答案 0 :(得分:3)

一般来说,没有。在event dispatch thread (EDT)以外的线程上绘制会导致不合需要的伪像,但结果可能是可接受的。这个example展示了一些权衡。我更喜欢使用javax.swing.Timer安排在EDT上绘图,但other approaches是可能的。此外,您选择的顶级Container可能已经实施了Buffer Strategy

答案 1 :(得分:2)

如垃圾邮件所述,这样做并不是一个好主意。创建自己的动画线程,绘制离屏图像。然后把它推到一些持有人。如果调用paintComponent获取当前图像并在组件上绘制它。完成。看看会合模式。