【问题标题】:Creating a loop that has a one second gap between loops [Handling Exceptions in the code]创建一个循环之间有一秒间隔的循环[处理代码中的异常]
【发布时间】:2020-03-25 00:55:20
【问题描述】:

我正在尝试创建一个倒数计时器,它将更新 Java 中的 Jlabel 以用于测验应用程序。到目前为止,我的代码有这个,但它给sleep() 方法提供了一个错误,并且没有运行我的程序。

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

【问题讨论】:

  • it gives an error - 什么错误?
  • 你是在主线程上运行这段代码吗?
  • Thread.sleep() 只能抛出InterruptedException
  • 这正是我添加它时所说的。中断异常
  • '未处理的异常类型 InterruptedException'

标签: java multithreading swing jlabel sleep


【解决方案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 尽可能。

【讨论】:

  • 肯定有一种更简单的方法,就是在一个循环中设置一个标签,等待 1 秒,然后更改标签中的值?
  • simple 完全是上下文相关的,3 行代码可能看起来很简单,但复杂程度不同。在并发世界中线程不是一件简单的事情。要指出一些,您不应该休眠参与用户交互的主/UI线程,并且您不能从后台/工作线程更新UI元素,因为UI元素是主线程受限的。这个列表还在继续......
【解决方案2】:

添加try catch块来捕获异常

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

           }

【讨论】:

  • 当我尝试程序根本不加载时。
猜你喜欢
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
相关资源
最近更新 更多