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 楼答案
Swing是单线程的。在
EDT
中调用Thread.sleep
可防止UI更新我建议改用Swing Timer。它被设计用来与Swing组件交互
编辑:
从计时器自身的
ActionListener
内停止计时器通常使用