-9

so I'm making the "Simon game" and I need a java code to pause the program for 0.5 sec to show to the user the buttons he needs to press on.

  greenButton.setBackground(Color.GREEN);
             //need to stop here
             press = true;
CrazyCat
  • 1
  • 1
  • 4
  • 1
    Possible duplicate of [Java Timer](http://stackoverflow.com/questions/1041675/java-timer) – SOFe Dec 30 '16 at 14:30
  • 6
    You need to provide more context - possibly a short code example. In general you could just use `Thread.sleep(500);`, but you mention buttons and if you wait on the GUI thread it will freeze the application. – assylias Dec 30 '16 at 14:30
  • My guess is that this is a Swing program and that you've tried thread sleep and found that it doesn't work. if so, use a Swing Timer, but why make us guess?? – DontKnowMuchBut Getting Better Dec 30 '16 at 14:32
  • yea you're right, I tried to use it and it doesn't work. how do I use "Swing Timer?" – CrazyCat Dec 31 '16 at 09:29

4 Answers4

1
Thread.sleep(500);

For more info, see this

leeyuiwah
  • 6,562
  • 8
  • 41
  • 71
1

You could use Thread.sleep(500) to wait for 0.5 seconds.....and in another thread display the buttons to the user.....Or you can set a volatile boolean flag which gets activated when you show the user the button he needs to click on....and which pauses all other thread....once the user clicks on the button the flag should be unset and all other threads should be notified.

prashant
  • 1,382
  • 1
  • 13
  • 19
  • Seeing your latest update...it would be good if you set up a wait notify mechanism...waiting for 500 milliseconds and till the user clicks the button...the click notifying the waiting thread to continue start running again. – prashant Dec 30 '16 at 14:36
0

Since this looks to be Swing, use a Swing Timer to pause without freezing the program.

int delayTime = 500; // for 500 msecs
new Timer(delayTime, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // TODO: code to be delayed goes here

        // stop the timer from repeating
        ((Timer) e.getSource()).stop();
    }
}).start();
0

You can use the CountDownLatch API https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html

For eg. In the first thread, create a latch with counter as 1 and pass it to the second thread that handles UI. Then in the first thread, call await() on the latch. This will cause the first thread to wait for the count to become zero. In parallel, in the second thread, you can handle he UI event and there you can do latch.countDown(). Once the count goes to zero, thread 1 will become active again. You can also provide a timeout in thread one. Thread One will come out of the wait and resume processing if the time out happens.

Vikram Rawat
  • 1,472
  • 11
  • 16