在 ActionListener 中使用 Thread.sleep() 的简单动画 [英] Simple animation using Thread.sleep() in ActionListener
问题描述
我在使用此代码创建轮盘时遇到问题.目标是当我点击旋转!"时旋转轮子.按钮.我通过创建一个 for 循环来完成此操作,该循环应该将轮子的状态从 true 更改为 false,从而更改方向.如果这样做足够快,应该会产生运动的错觉.
I'm having trouble with this code I am using to create a roulette wheel. The goal is to spin the wheel when I click the "SPIN!" button. I have done this by creating a for loop that should change the status of the wheel from true to false, which changes the orientation. This, when done fast enough, should create the illusion of movement.
我遇到的问题:尽管我放置了 repaint(),但我的轮子仅在整个 for 循环完成后才重新绘制.所以,它只旋转一个刻度.
THE PROBLEM I AM HAVING: is that my wheel is only repainting after the whole for loop is done, despite my placement of the repaint(). So, it only spins one tick.
这是我的 ActionListener 的一些示例代码:
Here is some sample code of my ActionListener:
public class spinListener implements ActionListener
{
RouletteWheel wheel;
int countEnd = (int)(Math.random()+25*2);
public spinListener(RouletteWheel w)
{
wheel = w;
}
public void actionPerformed(ActionEvent e)
{
for (int i = 0; i <countEnd; i++)
{
try
{
Thread.sleep(100);
if (wheel.getStatus() == true)
{
wheel.setStatus(false);
repaint();
}
if (wheel.getStatus() == false)
{
wheel.setStatus(true);
repaint();
}
}
catch (InterruptedException ex)
{
Logger.getLogger(WheelBuilder.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
更新:我发现了问题所在.以下是我为遇到类似问题的人所做的更改.
UPDATE: I figured out the problem. Here are the changes I made for anyone having a similar problem.
public class spinListener implements ActionListener
{
Timer tm = new Timer(100, this);
int count = 0;
public void actionPerformed(ActionEvent e)
{
tm.start();
changeWheel();
}
public void changeWheel()
{
int countEnd = (int)(Math.random()+20*2);
if (count < countEnd)
{
wheel.setStatus(!wheel.getStatus());
repaint();
count++;
}
}
}
推荐答案
Swing 是一个单线程环境,任何阻塞事件调度线程的事情都会阻止它处理新事件,包括绘制事件.
Swing is a single threaded environment, anything that blocks the Event Dispatching Thread, will prevent it from been able to process new events, including, paint events.
>
在 actionPerformed
方法中使用 Thread.sleep
会阻塞 EDT,阻止它处理新事件,包括绘制事件,直到 actionPerformed
方法已退出.
The use of Thread.sleep
within the actionPerformed
method is blocking the EDT, preventing it from processing new events, including paint events, until the actionPerformed
method is exited.
您应该使用 javax.swing.Timer
代替.
看看 Swing 中的并发 和 如何使用 Swing 计时器 了解更多详情
Take a look at Concurrency in Swing and How to Use Swing Timers for more details
这篇关于在 ActionListener 中使用 Thread.sleep() 的简单动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!