views:

221

answers:

2

I am looking into using Buffer Strategy and the 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.

+1  A: 

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.

trashgod
A: 

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.

Rastislav Komara