简体   繁体   English

如何使用Swing制作动画?

[英]How to make an animation with Swing?

I am making a JApplet and got stuck with a animation problem. 我正在制作一个JApplet并且遇到动画问题。

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. 有了这个,没有动画:在循环期间没有任何反应,repaint()方法似乎只在精灵停止移动时才会动作。

I would like to use only Swing for this, any ideas of how to proceed ? 我想只使用Swing,任何关于如何进行的想法?

Thanks for reading. 谢谢阅读。

You should use a javax.swing.Timer to perform the animation rather than Thread sleeps. 您应该使用javax.swing.Timer来执行动画而不是Thread睡眠。 Here is a good link to get you going: http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html 这是一个很好的链接,可以帮助您: 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. 此外,我强烈建议您购买Filthy Rich Clients一书 - 如果您访问该网站,您还可以免费下载所有示例代码。 For example, Chapter 12: Animation Fundamentals has some great examples, such as MovingButton that demonstrates the Timer usage. 例如, 第12章:动画基础知识有一些很好的例子,例如演示Timer用法的MovingButton。

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; 有一个Swing工作者线程负责显示你的东西; 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. 如果您正在从此线程外部更改图像,则可能无法获取更改,因为您未正确地与Swing线程同步。

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. 你需要使用像SwingUtilities.invokeLater(Runnable r)这样的东西来完成这个,你的图像改变代码将在r的run()方法中。 If you Google for "invokeLater" and Swing, chances are you'll find examples. 如果你谷歌为“invokeLater”和Swing,你很可能会找到例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM