开发者

Is it possible to perform active rendering in Java Swing without being on the EDT?

I am looking into using Buffer Strategy and th开发者_运维技巧e following technique described on the 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());

}

It would be great to avoid EDT and invokeLater or invokeAndWait when performing an animation.

My questions:

  • If this is in a Swing application don't we need to worry about putting the call to show on the EDT?
  • Can anyone else see any problems using this in a Swing app?

This was inspired by this interesting answer to game programming.


In general, no. Painting on a thread other than the event dispatch thread (EDT) results in undesirable artifacts, although the results may be acceptable. This example demonstrates some of the trade-offs. I prefer arranging to draw on the EDT using javax.swing.Timer, but other approaches are possible. Also, your chosen top-level Container may already implement a Buffer Strategy.


As mentioned by trashdog it is not good idea to do so. Create own animation thread which will draw off-screen image. Then push it to some holder. If paintComponent is called fetch current image and draw it on component. Done. Look at rendezvous pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜