繁体   English   中英

在for循环中使用thread.sleep

[英]Using thread.sleep in a for loop

我正在使用eclipse是否会有所作为。 我试图按一次按钮来更新标签10次,但我希望它在两次更新之间等待。 我正在尝试在for循环中使用thread.sleep,但是直到for循环结束时才更新标签。

该代码已接近。 它还包含更多代码来指定将标签更改为的内容。

for (int i = 0; i < 10; i++) {
    try{
        thread.sleep(250);
    }catch(InterruptedException ie) {
        return;
    }
    panel.repaint();
}

谢谢,真的很有帮助!

为了更新标签,主GUI事件循环必须轮到它了。 但是我猜您的代码正在主线程中运行,因此重绘图要等到您的代码完全完成后才能进行。

您需要做的是将睡眠循环放入一个单独的线程中。

对于此任务, SwingWorker类可能很有用。

Swing只有一个线程(通常称为Swing线程),所有按钮的按下,重画,处理,更新等都在该线程中进行。

这意味着,如果您阻塞该线程(例如,通过循环睡眠),则在完成之前无法重绘屏幕。

您需要将工作分配到另一个线程,例如通过使用SwingWorker或使用Timer来调度更新。 Swing有一个专门用于这种情况的Timer类,您可以告诉它每250ms回调一次,并在该回调中进行更改。

可能是我没有得到您的确切问题,否则下面是解决方案:

for (int i = 0; i < 10; i++) {
    try{
   panel.repaint();
        thread.sleep(250);
// Or here if you want to wait for 250ms before first update
    }catch(InterruptedException ie) {
        return;
    }
}

Thoguh SwingWorker是更好的选择。 将以上逻辑移至SwingWorker线程。 示例代码如下:

   class Task extends SwingWorker<Void, Void> {
        @Override
        public Void doInBackground() {
           for (int i = 0; i < 10; i++) {
               try{
                   panel.repaint();
                   thread.sleep(250);
                 // Or here if you want to wait for 250ms before first update
                  }catch(InterruptedException ie) {
                  }
           }
          return null;
        }

    /*
     * Executed in event dispatching thread
     */
    @Override
    public void done() {
      // Do something if you want at the end of all updates like turn off the wait cursor

    }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM