Reputation: 870
I have this piece of code
// If we click on an unfolded card
if (card.clicked == false) {
clicksCount++;
clickedCards[clicksCount - 1] = card;
card.showCardImage();
if (clicksCount == 2) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
// Loop through clicked cards and if they don't have the
// same ID fold them
if (clickedCards[0].cardID != clickedCards[1].cardID) {
for (int k = 0; k < clickedCards.length; k++) {
clickedCards[k].setDefaultIcon();
clickedCards[k].clicked = false;
}
failedAttempts.setText("Failed Attempts: "
+ ++failedCount);
}
attemptsCount++;
attempts.setText("Attempts " + attemptsCount);
clicksCount = 0; // reset click counter
}
}
It's function for my pexeso game. The first card shows card's image fine, but when I click for the second time it doesn't show image of it. It only waits and then fold the first card.
I know that it is because of sleeping the thread but don't know what should I do.
I'll be glad for any idea or advice.
Upvotes: 0
Views: 60
Reputation: 285405
I'm guessing that this is a Swing GUI (you never tell us). If so, then you're right: calling Thread.sleep(...)
on the Swing event thread will put the entire GUI to sleep, including all GUI drawing. Instead use a Swing Timer set to a delay of 1000 ms. In your Timer's ActionListener, you will change the card back to the original. You will tell the timer not to repeat via a setter method, setRepeats(false)
.
The Swing Timer Tutorial.
Upvotes: 1