Sleep occurs before previous statement execution?

Hi Everyone,

I'm writing a simple memory game in java for fun, as well as to learn a little more about java. I want it to work like a normal game of memory. Two cards are flipped, you have a few seconds to look at them provided they aren't a match, and then they flip back over.

So I have the cards in my memory game implemented as an extension of the JButton class. In the ActionListener for these JButtons/Cards, I have created a custom event, which the main program listens for. When a card is flipped, the main program checks to see how many cards are flipped, and if it's two it checks to see if they are matches.

If they aren't matches, it issupposed to wait three seconds and then flip the cards back over. I'm using Thread.sleep(3000), and the problem I'm having is that the application sleeps before it reaches the initial flip of the card. It's supposed to go CardFlipped>>Wait>>FlipBackOverIfNotMatch, but it's going Wait>>CardFlipped>>FlipBackOverIfNotMatch.

So I'm a little confused. The statement to flip the card and show it's contents is definitely before the Thread.Sleep command, but sleep happens first for some strange reason. If I throw in a JOptionPane.showMessageDialog after the statement to flip the card, everything works correctly. It's as if the application is "jumping the gun", and showing a message forces it to finish previous statements before sleeping.

Any Ideas? I could just find another way of doing it, but it bothers me that I can't figure out why this way doesn't work. Thanks in advance,

-Kyle

[1622 byte] By [KyleFxa] at [2007-11-27 0:19:59]
# 1

I don't do GUIs, and you haven't posted code, so I can't be sure of the details, but it sound like the sleep and the flip are in two different threads. You DO want you business logic to be separate from the thread that manipulates the GUI, so don't just go sticking random sleeps in the GUI thread.

If you have, in a single thread,

a();

sleep();

b();

then it will execute in the order you specify, with no surprising behavior.

I can't tell you exactly how to fix this, but I hope this will at least give you an idea of where to look.

jverda at 2007-7-11 22:12:29 > top of Java-index,Java Essentials,Java Programming...