Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

How do I create a timer that runs simultaneously with my trivia game without messing everything up?

+7 votes
I've tried many different ways to get a timer to work in my code. I feel as if there is an easier way to do this and I just can't figure it out. As of now I have made a timer method. Here is the current code:

public static double timer(double timeLeft, DrawingPanel panel) {       

    timeLeft = 30.0;

    for (double time = 1500.0; time >= 0.0; time--) {

            Graphics g = panel.getGraphics();


            g.drawRect(445, 535, 20, 20);


            g.setFont(new Font("Impact", Font.BOLD, 20));

            timeLeft = time/50;

            g.drawString("Time remaining: " + timeLeft, 350, 550);


            if (timeLeft == 0.0) {

            g.setFont(new Font("Impact", Font.BOLD, 25));

            g.drawString("OUT OF TIME!", 150, 450);

            g.drawString("Rerun the program to try again!", 150, 475);




    return timeLeft;


I am trying to pass the parameter timeLeft into my main trivia question method that runs the main part of my game (not the main method). But wherever I seem to put it, the timer method either starts and runs on its own before the question is presented, or runs with the question but the time is stacked on top of each other and does not clear after each second passes. Does anyone understand my dilemma and have any ideas on how to fix it?
asked Oct 27, 2016 in CSC 211 (F16) by Livy Zienty (100 points)
reshown Oct 27, 2016 by Forrest Stonedahl

1 Answer

+2 votes

You can't run the countdown timer in a separate method, because that method won't exit until the timer is finished, which means that nothing else (like your game play) can occur while the timer is running.

Instead, you'll need to have a variable that is counting down *during* your other code.

e.g. at the top of your main game loop, you probably need something like:

double timeLeft = 30.0;

And then inside of your loops where you are waiting for clicks or waiting for keyboard, you would need to have something like:

while (!panel.checkKeyboardInput() && panel.isVisible()) {


    timeLeft -= 0.1;

    g.drawString(...); // show the time remaining somewhere on the screen...


Except the only problem with this is that your text counter will keep getting drawn on top of the last text, so you probably need to put a g.fillRect() above the g.drawString(), which fills a box with color right underneath the text -- kind of like clearing a tiny bit of the panel (but not the whole panel) each time...

Hope that helps!



answered Oct 27, 2016 by Forrest Stonedahl (100 points)
Yes, this helps a lot! Thank you Professor Stonedahl.