java倒计时器_java – 使用计时器倒计时

本文探讨了在Java中创建倒计时计时器的问题。作者遇到的问题是计时器只执行一次,而不是按预期重复直到计数值减到0。在代码示例中,倒计时从3开始,但只显示了'3',没有继续显示'2'和'1',然后停止。解决方案在于正确配置和使用`Timer`以确保在倒计时结束前持续触发`ActionListener`。
摘要由CSDN通过智能技术生成

试图写一个计时器进行倒计时(如火箭发射:3-2-1-Go).我所拥有的似乎只执行一次.我需要它重复(几乎递归地)执行,直到值达到0.

正如您将看到的,我有各种println语句来跟踪这一进展.这是我的输出:

in Coundown constructor

in ActionListener

counting down

3

错在于我错过了以下输出:

2

1

Go

这告诉我这个计时器实际上并没有倒计时.它似乎在等待一秒然后终止.

如何在定时器达到零之前调用它?谢谢!

public class StopWatch {

JFrameMath myTest;

int seconds;

/* Constructor */

public StopWatch(JFrameMath thisTest, int sec) {

myTest = thisTest;

seconds = sec;

myTest.hideTestButtons(true);

Countdown display = new Countdown(myTest);

}

}

class Countdown extends JFrame implements ActionListener {

private Timer myTimer = new Timer(250, this);

JFrameMath myTest;

public Countdown(JFrameMath thisTest) {

System.out.println("in Coundown constructor");

myTimer.setInitialDelay(1150);

myTest = thisTest;

myTimer.start();

}

@Override

public void actionPerformed(ActionEvent e) {

System.out.println("in ActionListener");

int countSeconds = 3;

if(countSeconds == 0) {

myTest.showTimeRemaining("Go");

myTimer.stop();

System.out.println("done");

} else {

System.out.println("counting down");

myTest.showTimeRemaining(""+countSeconds);

countSeconds--;

}

myTimer.stop();

myTest.hideTestButtons(false);

}

}

public void showTimeRemaining(JFrameMath thisTest, String numSec) {

System.out.println(numSec);

lblCountdown.setText(numSec);

thisTest.pack();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值