我在使用此代码创建轮盘时遇到了麻烦。我的目标是当我单击“旋转”时旋转轮子。按钮。我通过创建一个for循环来完成此操作,该循环应将轮的状态从true更改为false,从而改变方向。如果做得足够快,这应该会产生运动的错觉。
我所遇到的问题:尽管我放置了repaint(),但我的轮子只在完成整个for循环后才重新绘制。因此,它只会旋转一个刻度。
这是我的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);
}
}
}
}
更新:我发现了问题。这是我为遇到类似问题的任何人所做的更改。
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是一个单线程环境,任何阻塞事件调度线程的事物都将阻止它处理新事件,包括绘画事件。
在Thread.sleep
方法中使用actionPerformed
会阻止EDT,从而阻止EDT处理新事件,包括绘画事件,直到退出actionPerformed
方法为止。
您应该改用javax.swing.Timer
。
查看Concurrency in Swing和How to Use Swing Timers以获得更多详细信息
关于java - 在ActionListener中使用Thread.sleep()进行简单动画,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23924373/