• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Triggering an animation from a button

 
Luigi Plinge
Ranch Hand
Posts: 441
IntelliJ IDE Scala Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another noob question... why does my moveBall() method work correctly from my runGui() method but not when called from my ActionListener class?

The call in MidiListener does run the method, but the GUI freezes and does not update until it's finished.

I think it's something to do with threads...?

 
Rob Camick
Ranch Hand
Posts: 2565
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Code invoked from an event listener executes on the Event Dispatch Thread. The Thread.sleep() tells the EDT to sleep so the GUI can't repaint itself.

Read the section from the Swing tutorial on Concurrency for a more detailed explanation and a possible solution.

However a better solution is to use a Swing Timer for animation. The tutorial also contains a section on "How to Use Timers".
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're starting with Swing, you may not know about the Event Dispatch Thread yet. This is a thread where all Swing events are being processed.

The first version of your program calls Thread.sleep on the current thread, which does not affect the Event Dispatch Thread. The second version of your program uses an ActionListener, which will be executed in the Event Dispatch Thread. This means that this time, Thread.sleep is invoked in the Event Dispatch Thread, which is going to block all other painting events, causing the freeze that you are experiencing.

In moveBall, try to add something like System.out.println(Thread.currentThread().getName()) to see the difference.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Luigi, if you have further Swing related questions, please post them in the Swing forum. Thank you
 
Luigi Plinge
Ranch Hand
Posts: 441
IntelliJ IDE Scala Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Many thanks, both of you. I'll have a look at the Swing tutorial mentioned.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic