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

我正在研究使用缓冲策略和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()); 

}

在执行动画时避免使用EDT和invokeLaterinvokeAndWait会很棒。

我的问题:

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

这是受到这个有趣的游戏编程答案的启发。

一般来说,没有。 在事件调度线程(EDT)以外的线程上绘制会导致不希望的伪像,尽管结果可能是可接受的。 这个例子展示了一些权衡。 我更喜欢使用javax.swing.Timer安排在EDT上绘图,但其他方法也是可行的。 此外,您选择的顶级Container可能已经实施了缓冲策略 。

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