Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

java - How to make an animation with Swing?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...