File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes Triggering an animation from a button Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Triggering an animation from a button" Watch "Triggering an animation from a button" New topic
Author

Triggering an animation from a button

Luigi Plinge
Ranch Hand

Joined: Jan 06, 2011
Posts: 441

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

Joined: Jun 13, 2009
Posts: 2091
    
    7
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

Joined: Nov 24, 2005
Posts: 14687
    
  16

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.


[My Blog]
All roads lead to JavaRanch
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

Luigi, if you have further Swing related questions, please post them in the Swing forum. Thank you
Luigi Plinge
Ranch Hand

Joined: Jan 06, 2011
Posts: 441

Many thanks, both of you. I'll have a look at the Swing tutorial mentioned.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Triggering an animation from a button
 
Similar Threads
GUI Problem
Animation in Java
Why am I getting a copy of a button in my JPanel?
Help me understand Inner Classes with code example provided
Problem with Graphics