在循环中调用Thread.sleep - 在重新绘制组件时使用延迟的正确方法是什么?

时间:2013-08-13 12:22:32

标签: java swing

我创建了循环,定期重新绘制组件:

public class A extends Thread {

  private Component component;
  private float scaleFactors[];
  private RescaleOp op;

  public A (Component component){
  this.component = component;
  }

  public void run(){

    float i = 0.05f;
    while (true) {

        scaleFactors = new float[]{1f, 1f, 1f, i};
        op = new RescaleOp(scaleFactors, offsets, null);

        try {
            Thread.sleep(timeout);
        } catch (InterruptedException ex) {
            //Logger.getLogger(...)
        }
        component.repaint();
        i += step;
      }

    }

}

但在这种情况下,我收到消息(NetBeans 7.3.1):

  

在循环中调用Thread.sleep

在这种情况下可能有更好的解决方案吗?

1 个答案:

答案 0 :(得分:6)

Swing是单线程的。在Thread.sleep中调用EDT会阻止UI更新。

我建议改用Swing Timer。它旨在与Swing组件进行交互。

Timer timer = new Timer(timeout, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        component.repaint();
    }
});
timer.start();

编辑:

通常使用

在自己的ActionListener内停止计时器
@Override
public void actionPerformed(ActionEvent e) {
    Timer timer = (Timer) e.getSource();
    timer.stop();
}
相关问题