0

In Java, I can use sleep(x) to delay some code from running for x seconds. But, if I'm using Swing, that makes my GUI freeze, so it's not an ideal solution.

How can one create a delay before running a sequence of code in Java?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
owlswipe
  • 19,159
  • 9
  • 37
  • 82
  • 1
    How is your code set up? Are you using the SwingWorker threads like you're supposed to? https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html – Brick Feb 10 '17 at 01:28
  • @Brick I'm not, as I'm making a very simple program and just trying to delay the change of a label (not of a heavy background task). I did figure it out myself, and I posted my own answer below. – owlswipe Feb 10 '17 at 01:30
  • This question is almost the exact same as [this popular question of mine](http://stackoverflow.com/questions/38031137/how-to-program-a-delay-in-swift-3/38031138#38031138), just that I'm talking about java instead of swift. – owlswipe Feb 10 '17 at 01:32
  • 2
    The canonical Swing solution is to use a Swing Timer. Your posted solution is overly complex, potentially dangerous in that it risks running Swing code off the event thread, and so should not be recommended as an answer on this site. – Hovercraft Full Of Eels Feb 10 '17 at 01:52

1 Answers1

0

To start, you probably shouldn't be doing whatever you're doing in the display thread. If it were in your own thread, the GUI wouldn't freeze. But short of revisiting your entire thread strategy, the usual workaround is to add a queue of tasks to be run later.

ddyer
  • 1,792
  • 19
  • 26