2014-04-11 65 views
0

Hy! 所以我開始與NetBeans的Java GUI開發,我遇到了這個問題:暫停Swing GUI

我做了一個按鈕和文本字段的窗口。當用戶點擊按鈕時,我希望文本框開始輸入延遲。因此,例如:

textfield.text=h 
wait(1) sec 
textfield.text=he 
wait(1) sec 
textfield.text=hel 
wait(1) sec 
textfield.text=hell 
wait(1) sec 
textfield.text=hello 

我已經嘗試與Thread.sleep(),但在上面的例子中等待4秒鐘或左右,顯示整個文本(所以它不是給我的錯字效果,我想)後。

有人可以幫助我嗎?

+0

看看這個答案,實現一個Swing定時器專門做你想做的事情。 http://stackoverflow.com/a/13198256/2142219 – Matthew

回答

5

如果您使用Thread.sleep(...)或任何延遲Swing事件線程的其他代碼,您最終會將整個Swing事件線程置於睡眠狀態,並將其與您的應用程序一起使用。這裏的關鍵是改爲使用Swing Timer。在Timer的ActionListener的actionPerformed方法中,添加一個字母並增加索引,然後使用該索引來決定下一個要添加的字母。

String helloString = "hello"; 

// in the Timer's ActionListener's actionPerformed method: 
if (index >= helloString.length()) { 
    // stop the Timer here 
} else { 
    String currentText = textField.getText(); 
    currentText += helloString.charAt(index); 
    textField.setText(currentText); 
    index++; 
} 
+0

你能寫一個適合我的例子的代碼的完整例子嗎?我真的很感激。 – user2580136

+4

@ user2580136:不,請相信我,您將獲得更多***,並通過使用我的想法和自己編寫完整的示例代碼來學習更多。那麼如果你遇到困難,請回過頭來看你的代碼和你的問題。我已經給你一個鏈接到[Swing Timer教程](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html),所以請給出一個看看。祝你好運! –

+0

我會嘗試,但我恐怕最終會流下很多眼淚:/ – user2580136

0

得到它通過使用像這樣的工作:

Timer a,b,c 

Timer c=new Timer(500, new ActionListener(){public void actionPerformed(ActionEvent e){textfield.setText(abc)}}) 

Timer b=new Timer(500, new ActionListener(){public void actionPerformed(ActionEvent e){textfield.setText(ab);c.start()}}) 

Timer a=new Timer(500, new ActionListener(){public void actionPerformed(ActionEvent e){textfield.setText(a);b.start()}}) 

a.setRepeats(false); 
b.setRepeats(false); 
c.setRepeats(false); 

a.start() 

有誰知道有可能相同的效果更簡單的方法?