How to create a delay in Swing

Fractaly picture Fractaly · Aug 31, 2011 · Viewed 15k times · Source

I made a blackjack game, and I want the AI player to pause between taking cards. I tried simply using Thread.sleep(x), but that makes it freeze until the AI player is done taking all of his cards. I know that Swing is not thread safe, so I looked at Timers, but I could not understand how I could use one for this. Here is my current code:

while (JB.total < 21) {

          try {
            Thread.sleep(1000);
          } catch (InterruptedException ex) {
            System.out.println("Oh noes!");
          }

          switch (getJBTable(JB.total, JB.aces > 0)) {
            case 0:
              JB.hit();
              break;
            case 1:
              break done;
            case 2:
              JB.hit();
              JB.bet *= 2;
              break done;
          }
        }

BTW, the hit(); method updates the GUI.

Answer

camickr picture camickr · Aug 31, 2011

so I looked at Timers, but I could not understand how I could use one for this

The Timer is the solution, since as you say you are updating the GUI which should be done on the EDT.

I'm not sure what your concern is. You deal a card and start the Timer. When the Timer fires you decide to take another card or hold. When you hold your stop the Timer.