Animation with javax.swing.Timer Problem
Hi,
In my program I modify a data structure (a two dimensionaly array) several times based on a single MouseEvent and an "observer" of this array animates the modificantions applied to this array one after the other. So my code looks like:
firstModify();
// Modifies the array
notifyFirstModify();
/*-> invokes the firstAnimate() in my observer to animate the changes applied to the array */
secondModify(); // Modifies the array
notifySecondModify()
/* -> invokes the secondAnimate() in my observer to animate the changes applied to the array */
The animation methods (firstAnimate() and secondAnimate()) use the javax.swing.Timer to drive the animation. All of the code listed above executes in the Event Handling Thread.
THE BIG problem is that notifyFirstModify() and notifySecondModify() execute asynchronously, ie. they return immediately before the animation has even started. As a result new modifications are introduced to the array (by secondModify()), before I was able to show/complete the animation presenting the initial updates applied to the array (by firstModify()).
Clearly I should restructure my program's logic. Please let me know how.
I don't really want to lock up my event handling thread waiting for the animation to complete. Is this the only choice I have.
Thank you.
You can add an event queue (FIFO, of course) at your event handler.
Your handler could handle new events added to the queue meanwhile it was handling another even, after the handling process finish.
The "read events" and "add event" methods of that queue should be monitorized (readers-writers problem of concurrent programming)
Hi elquebuscamascosas,
Thanks for your input. Here is some informatin. I have one single thread: the event handling thread, which starts a javax.swing.Timer (this operation is asynchronous) to drive my animations which depend on the current state of the game as expressed in the game's internal matrix.
The event handling thread after creating and invoking the Timer (which is asynchronous) continues with the game and invokes certain functions which mofidy the state of the game. As a result when the animation/animations start the modications that they should animate have been overwritten.
I can sure queue all the events, unfortunately when I start processing them the state of the game (most probably) would have changed.
Thanks for your input
hi elquebuscamascosas,
Yes this is the approach that I started looking into yesterday. One problem that I ran into is that my animations will start overlapping. In other words:
updateState1();
storeTheStateAndAnimate1();
updateState2();
storeTheStateAndAnimate2();
.
.
.
In other words I can't guarantee that animationN will complete before animationN+1 starts.
Thanks for your valuable input. It's suprising how such a simple project created such a headache for me.