Search code examples
javatimerapplet

How to create a countdown timer in a Java Applet?


I'm working on a final project for school with a Java applet that counts down from a given interval to zero. When a Rectangle on screen experiences a mouse down event, it is supposed to execute the timer; however this does not occur; the program ends up crashing. I've seen a lot of examples of timers online, but many are using Java's built in timer class, which I am not using. I figured there must be a more basic way to do a simple timer. All variables have been declared at the top of the class.

public boolean mouseDown(Event e, int x, int y)
    {
    if(start.inside(x,y))
    {
        timerAct = true;
        startTime = System.currentTimeMillis() / 1000;
        endTime = startTime + interval;

        while (System.currentTimeMillis() / 1000 < endTime) {
            while (startTime != System.currentTimeMillis() / 1000) {
                startTime += 1;
                timeLeft = (endTime - startTime);
            }
        }
        timerAct = false;
    }
    repaint();
    return true;
}

The logic seems to workout okay because this began as System.out.println(), and it worked just fine. Then, it was converted to store the variable timeLeft. In the paint method, I have

    g.drawString("Time: " + timeLeft, 420, 180);

to print the the time remaining. I also have the update method; but it doesn't seem to make a difference. And I know the issue isn't because I'm changing a variable. My mouse down method has an if statement with a different rectangle that tracks clicks (not shown), and it updates a counter of clicks on screen in the applet window without any issue. Any help is greatly appreciated.


Solution

  • Check this. It's pretty self explanatory.