How to make an animation with Swing?

2019-01-20 03:17发布

问题:

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.

回答1:

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.



回答2:

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.