2015-09-20 74 views
1

在我的程序中,我試圖通過在label.setText()調用之間使用Thread.sleep(3000)幾秒後更新JLabelThread.sleep運行不正常

public void actionPerformed(ActionEvent e) 
{ 
    gameUpdate.label.setText("text a"); 
    try {     
     Thread.sleep(3000);     
    } 
    catch (InterruptedException ie) 
    { 
     ie.printStackTrace(); 
    } 
    gameUpdate.label.setText("text b"); 
} 

按下按鈕並且標籤不更新會發生什麼。然後在3秒後標籤更新爲「文字b」。我不明白爲什麼會發生這種情況。

+4

在Swing應用程序的[EDT(Event Dispatch Thread)](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html)上執行** not **'sleep' 。 –

回答

3

我不明白爲什麼會發生這種情況。

您正在調用ActionListener中的代碼,並且此代碼在事件調度線程(EDT)上執行。

Thread.sleep(...)會導致EDT進入睡眠狀態,這意味着在完成睡眠之前GUI無法重新繪製自己。

您需要使用單獨的線程。查看Concurrency的Swing教程中的部分了解更多信息。您可以使用SwingWorkerpublish結果。

或者,另一種選擇是使用Swing Timer安排文本的更新。該教程還有一個關於How to Use Timers的部分。

+1

使用擺動計時器可能更適合這種情況。看看[如何使用Swing定時器](https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html)。 – Andreas