0

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.

3
  • 1
    what is card (my crystal ball is asking if cardID a String) Commented Mar 28, 2014 at 19:04
  • 1
    Also you might want to use a debugger and figure out by yourself (or narrow down the issue) Commented Mar 28, 2014 at 19:04
  • @RC.: A debugger, while usually useful, would not help here, since the program's logic would work just fine, but the the cause of the problem, the Thread.sleep(...) freezing the Swing event dispatch thread (EDT) and thus freezing Swing graphics, would be something that would be very hard to isolate with a standard debugger. Commented Mar 28, 2014 at 19:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much that's exactly what I wanted to know :) and for next time I'll tell which gui it is :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.