创建一个在循环之间有一秒间隔的循环[处理代码中的异常]

问题描述 投票:0回答:3

我正在尝试创建一个倒数计时器,该计时器将为测验应用程序更新Java中的jlabel。到目前为止,我的代码已经有了这个,但是它给sleep()方法带来了错误,并且无法运行我的程序。

    while (timer > 0) {
     lblTimer.setText(Integer.toString(timer));
     Thread.sleep(1000);
     timer--;

    }
java loops jlabel sleep
3个回答
1
投票
class JlabelUpdater {
   private JLabel label;
   private Integer timerTickCount;
   private Integer tickerIntervalInMillis;
   private ScheduledExecutorService scheduledExecutorService = 
           Executors.newScheduledThreadPool(1);

   public JlabelUpdater(JLabel label, Integer timerTickCount, 
                        Integer tickerIntervalInMillis) {
      this.label = label;
      this.timerTickCount = timerTickCount;
      this.tickerIntervalInMillis = tickerIntervalInMillis;
   }

   public void startTimer() {
     scheduledExecutorService.scheduleAtFixedRate(() -> {
        if (timerTickCount == 0) {
           scheduledExecutorService.shutdown();
        }

        System.out.println("timer running: " + timerTickCount);
          changeText(timerTickCount + "");
          timerTickCount--;
         }, 0, tickerIntervalInMillis, TimeUnit.MILLISECONDS);
   }

   private void changeText(final String text) {
      EventQueue.invokeLater(() -> {
             label.setText(text);
             System.out.println("text = " + text);
         }
      );
   }
}

如果您想要一个5秒钟的计时器并每1秒更新一次JLabel文本,则可以创建此类的对象并像这样调用它。

new JlabelUpdater(new JLabel(), 5, 1000).startTimer();

始终建议使用ScheduledExecutorService而不是Timer只要有可能。


0
投票

添加尝试捕获块以捕获异常

     while (timer > 0) {
            lblTimer.setText(Integer.toString(timer));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            timer--;

           }

0
投票

您需要执行以下一项操作:

A。用[try / catch]包围Thread.sleep|(1000)

while (timer > 0) {
    lblTimer.setText(Integer.toString(timer));
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    timer--;
}

B。在您编写了throws InterruptedException的方法的签名中附加Thread.sleep(1000);

© www.soinside.com 2019 - 2024. All rights reserved.