我正在尝试创建一个倒数计时器,该计时器将为测验应用程序更新Java中的jlabel
。到目前为止,我的代码已经有了这个,但是它给sleep()
方法带来了错误,并且无法运行我的程序。
while (timer > 0) {
lblTimer.setText(Integer.toString(timer));
Thread.sleep(1000);
timer--;
}
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
只要有可能。
添加尝试捕获块以捕获异常
while (timer > 0) {
lblTimer.setText(Integer.toString(timer));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
timer--;
}
您需要执行以下一项操作:
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);
。