user2914137
user2914137

Reputation: 1

Java sleep acts too early

sleep starts before I want it to...

So I have this button with an event-mouse click to show the number in m[0][0] and then proceeds with an if

private void m00MouseClicked(java.awt.event.MouseEvent evt) {     

m00.setText(String.valueOf(m[0][0]));
c=c+1;
if(c==2){
.......
}

but i would like the button to show the number m[0][0] then wait a few seconds before continuing with the if and ive tried:

private void m00MouseClicked(java.awt.event.MouseEvent evt) {     

m00.setText(String.valueOf(m[0][0]));
c=c+1;
try {
    Thread.sleep(2000);
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}
if(c==2){
.......
}

but where ever I place the try-sleep it waits the 2 seconds before showing the number and continuing with the if, ive even tried the sleep inside the if but still doesnt work the way I want. HELP PLEASE!!

Upvotes: 0

Views: 200

Answers (1)

camickr
camickr

Reputation: 324147

Don't invoke Thread.sleep() from inside a listener. The code will execute on the Event Dispatch Thread which causes the GUI to freeze.

Instead you can use a Swing Timer to schedule an event to occur in 2 seconds. Read the section from the Swing tutorial on How to Use Swing Timers for more information.

Upvotes: 4

Related Questions