0

我创建了循环,它会定期重绘组件:

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 在循环中调用

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

4

1 回答 1

6

Swing 是单线程的。调用阻止 UI 更新Thread.sleepEDT

我建议改用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();
}
于 2013-08-13T12:24:42.353 回答