• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Nested Swing Timers?

 
Chris Crawford
Ranch Hand
Posts: 96
Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I searched both this forum and the Web for something addressing this issue, because I'm sure that somebody else has encountered and solved it before me, but I had no luck -- perhaps I was using the wrong search terms ("Java", "Timer", "nested"). Anyway, I'm having a problem with two Swing Timers. The actionPerformed method for the first timer ("npcHangsUpTimer") contains a call to a method that starts the second timer ("quickieTimer"). Here are the relevant code fragments:



After reading and re-reading the Oracle docs on Swing.Timer, I came to the conclusion that there's something bad about multiple timers at work simultaneously. This should not be the case with my code (the timer npcHangsUpTimer is stopped BEFORE the timer quickieTimer is started). But the various experiments I have tried demonstrate clearly that I cannot run quickieTimer from inside method runNPCTurn() AND have the program execution inside runNPCTurn() halt until quickieTimer releases it.

I am tempted to rewrite the code to separate this execution into independent phases running at a higher level of execution, but that will be a lot of work. Can anybody see one of those slap-yourself-on-the-side-of-the-head mistakes that can readily be repaired? Have I failed to understand something fundamental about Swing Timers?
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> I came to the conclusion that there's something bad about multiple timers at work simultaneously.

you have multiple conditions to be met before the timers will fire.
are you sure they do get called? (i.e. a couple of sys.out.println's)

here's a very simple demo of of one calling the other
(with a slight mod, assuming your timer.stop() means you only want it to run once)



you need to create a (similar) simple demo of your code so we can run it, see if/how the conditions are met,
and see it (not) working correctly
 
Chris Crawford
Ranch Hand
Posts: 96
Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Michael, for the help. I went ahead and implemented the setRepeats() change. Interestingly enough, I had gotten the use of the stop() method from an example I found on the web; it must have been ancient. Then I saw it while going through the Oracle docs on Swing.Timer, but ignored it because I had larger fish to fry.

Anyway, I ended up resolving the problem by a restructuring of the code that replaced the nesting with a properly serial execution. As an old friend -- and much better programmer -- once told me, the best solution to a seemingly intractable problem is usually to restructure the code.

Thanks again for the help.

Chris
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic