[英]Simple Java countdown timer
我正在用 Java 做一个学校项目,需要弄清楚如何创建一个计时器。 我正在尝试构建的计时器应该从 60 秒开始倒计时。
您可以使用:
int i = 60;
while (i>0){
System.out.println("Remaining: "i+" seconds");
try {
i--;
Thread.sleep(1000L); // 1000L = 1000ms = 1 second
}
catch (InterruptedException e) {
//I don't think you need to do anything for your particular problem
}
}
或类似的东西
编辑,我知道这不是最好的选择,否则你应该创建一个新类:
public class MyTimer implements java.lang.Runnable{
@Override
public void run() {
this.runTimer();
}
public void runTimer(){
int i = 60;
while (i>0){
System.out.println("Remaining: "+i+" seconds");
try {
i--;
Thread.sleep(1000L); // 1000L = 1000ms = 1 second
}
catch (InterruptedException e) {
//I don't think you need to do anything for your particular problem
}
}
}
}
然后你在你的代码中做: Thread thread = new Thread(MyTimer);
查看Timer 、 ActionListener 、 Thread
有很多方法可以做到这一点。 考虑使用 sleep 函数并让它在每次迭代之间休眠 1 秒并显示剩余的秒数。
由于您没有提供详细信息,因此如果您不需要它完全准确,这将起作用。
for (int seconds=60 ; seconds-- ; seconds >= 0)
{
System.out.println(seconds);
Thread.sleep(1000);
}
用Java倒计时很简单。 假设你想倒计时 10 分钟,所以试试这个。
int second=60,minute=10;
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
second--;
// put second and minute where you want, or print..
if (second<0) {
second=59;
minute--; // countdown one minute.
if (minute<0) {
minute=9;
}
}
}
};
new Timer(delay, taskPerformer).start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.