views:

419

answers:

2

How should I run animation in a Swing applet?

I have an animation thread performing active rendering and it initially animates fine. Sometimes (anywhere from 1 minute to 2 hours later) it begins to fail to update the screen and only the sounds occur. I believe this is due to the fact that the paint is not performed from the EDT causing some kind of concurrency problem.

So, should the active rendering (ie getGraphics() and painting) be called only from the EDT? A problem with this is the Swing timer lacks precision.

Or has anyone had success with active rendering without using the EDT, and completely disabling any EDT updates to the page (maybe using Canvas / or ignore repaint on a JPanel)?

+2  A: 

You can paint graphics into your own off-screen image in another thread and copy to the screen in the EDT. But for single threaded stuff, I would hope your frame rate is high enough to be able to do it in the EDT.

Tom Hawtin - tackline
Thanks Tom, the problem is still that the EDT through the Swing timer is lacking precision regardless of how much or little work is performed on the timer.Here are some samples in ms between calls (method just records time) when asking for 60fps. This is unacceptable.1932291828192844727
Pool
Yeah, the Swing timer resolution is poor (at least on some platforms). But you can run a proper scheduler on another thread and invoke later (which is almost how Swing Timer) is implemented.
Tom Hawtin - tackline
I mistakenly assumed that the invoke later would be as unreliable as the swing timer. It's not, it's accurate. Now just some work with yielding and preventing the invoke laters backing up and it should be there. Thanks for the advice.
Pool
There is no deliberate delay in invokeLater, although it may be late if the GUI is busy. IIRC, it's wait in particular that is unreliable for Swing Timer (as well as currentTimeMillis). So just be careful to hack around the problems in your scheduler thread.
Tom Hawtin - tackline
+1  A: 

A few things to look at would be to make sure you are only repainting what needs to be repainted and not the whole graphics context each time unless necessary. Also there is a timing framework that you can use to handle some animations. I don't think it is actively being developed but last time I looked at it it had some nice api's to use for animation.

Without knowing your specific use case this is all I could come up w/ off the top of my head.

broschb
Thanks, actually the timing framework and optimisation (including clipping) is pretty mature as the Swing applet is basically being converted from AWT. Replacing active rendering with invokeLater and sleep(1) until invoke has been carried out is a simple swap that slots in the old code.
Pool