有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java线程。在循环中调用sleep在重新绘制组件时使用延迟的正确方法是什么?

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

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 called in loop

也许在这种情况下有更好的解决方案


共 (1) 个答案

  1. # 1 楼答案

    Swing是单线程的。在EDT中调用Thread.sleep可防止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();
    }