How to make a simple timer using Timeunit.Sleep

Asked

Viewed 738 times

0

I am beginner in Java and was trying to make a mathematical game whose theme was to add the random numbers of the buttons (of course the person would have the help of the numbers 1, 2 and 5) until arriving at a value equal to the random number generated automatically (better than a simple calculator).

The only thing I miss, until the moment, is a timer to give the game another level of difficulty. However, I tried to make a simple timer to test if I could do with TimeUnit.Sleep and it didn’t go very well.

In this case, the Jlabel lblGameTime take the value of seconds (60) and go down 1 every second with the open game, if the person could equal valorSomado with valorRandomico, the program would randomize the Buttons value and valorRandomico again and the time would have an additional 30 seconds (but this idea is another method I’m still going to do, I just quoted to supplement the question)

public void GameTime() {
    int seconds = 60;
        for (int i = seconds; i < 0; i++) {
            lblGameTime.setText(String.valueOf(i));
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException ex) {
            Logger.getLogger(tela1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

variable valorSomado:

private int valorSomado = 0;

Method valorRandomico:

private long randomNumber() {
    long ale;
    ale = (long) ((Math.random()) * (10001 - 0) + 1);
    lblRandomNumber.setText(String.valueOf(ale));
    return ale;
}

PS: The "Swing" that I’m using is the one from NetBeans that already comes with a separate screen where da to model the entire screen on which the code will be executed

imagem do tal "<code>Swing</code>" do <code>NetBeans</code>

PSS: I had the "brilliant" idea of trying not to use classes (even though I know I’m using Java )

descrição mal feita

  • For informational purposes only, the swing is a java API, not netbeans API. What you see builds screens in the style drag 'n drop is the Builder GUI, which uses the swing directly from the JDK.

  • Thanks for telling me this @Diegof, one more thing to memorize, hehe

  • If I’m not mistaken, there is a Timer class in the swing, I just don’t remember how to use it. When I can, if no one has answered, I try to answer something.

  • I’ll take a look at this @Diegof class, thanks again

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.