Reputation: 733
I'm working on a school project in Java and need to figure out how to create a timer. The timer I'm trying to build is supposed to count down from 60 seconds.
Upvotes: 2
Views: 22827
Reputation: 1518
It is simple to countdown with Java. Lets say you want to countdown 10 min so Try this.
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();
Upvotes: 0
Reputation: 175
You can use:
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
}
}
Or something like that
EDIT, i Know this is not the best option, otherwise you should create a new class:
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
}
}
}
}
Then you do in your code: Thread thread = new Thread(MyTimer);
Upvotes: 3
Reputation: 7215
Since you didn't provide specifics, this would work if you don't need it to be perfectly accurate.
for (int seconds=60 ; seconds-- ; seconds >= 0)
{
System.out.println(seconds);
Thread.sleep(1000);
}
Upvotes: 2
Reputation: 329
There are many ways to do this. Consider using a sleep function and have it sleep 1 second between each iteration and display the seconds left.
Upvotes: 0