如何使用 Swing 制作动画? [英] How to make an animation with Swing?
问题描述
我正在制作 JApplet,但遇到了动画问题.
I am making a JApplet and got stuck with a animation problem.
这是我的代码:
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){
}
}
有了这个,就没有动画了:在循环过程中什么也没有发生,repaint() 方法似乎只在精灵停止移动时才起作用.
With this, there is no animation : nothing happens during the loop, the repaint() method seems to only act once the sprite stopped moving.
我只想为此使用 Swing,对如何进行有任何想法吗?
I would like to use only Swing for this, any ideas of how to proceed ?
感谢阅读.
推荐答案
您应该使用 javax.swing.Timer
来执行动画而不是线程休眠.这是一个很好的链接,可以帮助您:http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html
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
另外,我强烈建议您购买肮脏的富客户——如果您访问该网站,您也可以下载所有示例代码都是免费的.例如,第 12 章:动画基础 有一些很好的例子,例如演示 Timer 用法的MovingButton.
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.
这篇关于如何使用 Swing 制作动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!