views:

235

answers:

2

Hi,

I am making a JApplet and got stuck with a animation problem.

Here is my code :

  this.sprite.setBounds(0,0,20,17);
  this.sprite.setIcon(this.rangerDown);
  for(int i = 0; i< 16;i++)
  {
   this.sprite.repaint();
   this.sprite.setLocation(this.sprite.getX(), this.sprite.getY()+10);
   try{
    Thread.currentThread().sleep(100);
   }catch(InterruptedException e){
   }
  }

With this, there is no animation : nothing happens during the loop, the repaint() method seems to only act once the sprite stopped moving.

I would like to use only Swing for this, any ideas of how to proceed ?

Thanks for reading.

+2  A: 

You should use a javax.swing.Timer to perform the animation rather than Thread sleeps. Here is a good link to get you going: http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html

Also I highly recommend buying the book Filthy Rich Clients -- if you go to the website you can also download all the example code for free. For example, Chapter 12: Animation Fundamentals has some great examples, such as MovingButton that demonstrates the Timer usage.

Chris B.
It's perfectly acceptable to sleep() in the image-changing thread, so long as that thread has nothing better to do and so long as that thread is not the Swing worker thread, which must be left to do its work undisturbed :)
Carl Smotricz
@Carl -- true :) Most docs and articles on Java animation prefer the Timer class though. Here's a good Sun article that talks about both approaches for animation: http://java.sun.com/products/jfc/tsc/articles/timer/ (search for "sleep" to see some of the comparisons).
Chris B.
It worked, thanks a lot !
Cheshire
A: 

You left out the code surrounding your code, that makes it a little harder to help you.

You most likely have a problem with thread handling. There's a Swing worker thread responsible for displaying your stuff; if you're sleeping inside that thread it's not able to do its work. If you're changing the image from outside this thread, then it may not be picking up the change because you're not properly synchronizing with the Swing thread.

You need to use something like SwingUtilities.invokeLater(Runnable r) to accomplish this, where your image-changing code would be in r's run() method. If you Google for "invokeLater" and Swing, chances are you'll find examples.

Carl Smotricz