2014-04-11 66 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() 

有谁知道有可能相同的效果更简单的方法?