2014-03-28 62 views
0

我有這樣一段代碼代碼不執行

// 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 

    } 
} 

這功能我pexeso遊戲。第一張牌顯示卡的圖像很好,但是當我第二次點擊時,它不顯示圖像。它只是等待,然後摺疊第一張牌。

我知道這是因爲睡覺的線程,但不知道該怎麼辦。

我會很高興任何想法或建議。

+1

什麼是'卡'(我的水晶球在問'cardID'是否是一個字符串) – 2014-03-28 19:04:02

+1

你也可能想使用一個調試器並自己弄清楚(或縮小問題) – 2014-03-28 19:04:45

+0

@RC .:調試器,雖然通常很有用,但在這裏並沒有什麼幫助,因爲程序的邏輯工作得很好,但是問題的原因,Thread.sleep(...)凍結了Swing事件調度線程(EDT),從而凍結了Swing圖形,將是很難與標準調試器隔離的東西。 –

回答

1

我猜這是一個Swing GUI(你永遠不會告訴我們)。如果是這樣,那麼你是對的:在Swing事件線程上調用Thread.sleep(...)將使整個GUI進入休眠狀態,包括所有GUI繪圖。取而代之的是使用設置爲1000毫秒延遲的擺動計時器。在您的定時器的ActionListener中,您將把卡更換回原來的位置。你會告訴計時器不要通過setter方法重複,setRepeats(false)

The Swing Timer Tutorial

+0

非常感謝,這正是我想知道的:)並且下次我會告訴它是哪個gui:D – user13746

+0

@ user13746:不客氣。祝你好運! –