-1

I am writing a Poker program using Java, and I want to add a delay to my program to add some style to it. Just one problem: I don't know how to do that.

What I am looking for is kind of like Python with the "sleep()" function.

I have tried googling it, but the code I got was either extremely outdated or just straight up doesn't work. Can someone help me?

TimMcYeah
  • 121
  • 6

2 Answers2

0

There's a static method sleep in the Thread class. However, if you're running a UI application, be careful not to block your UI thread.

Jorn
  • 20,612
  • 18
  • 79
  • 126
0

If your program is a console application you can just use Thread.Sleep(milliseconds)

Or if you want to use something simpler, use TimeUnit.SECONDS.sleep(seconds).

However if you are making a GUI application for Javax.Swing, using these will also stop the rendering of the GUI. So in that case you want to use a Swing Timer. For that you can use:

Timer timer = new Timer(5000, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {            
        aDiffrentMethod();
    }
});
timer.setRepeats(false);
timer.start();

For more Information, see How to Use Swing Timers.

Mac.exe
  • 1
  • 5
  • Thank you for your answer! Just one thing; does the TimeUnit class come from a package or is it built-in like the Math class? – TimMcYeah May 16 '23 at 15:23
  • @JellyTheTitan Its in ```java.util.concurrent.TimeUnit```. Btw accept the answer you liked so it's easier to get the answer. – Mac.exe May 16 '23 at 15:44