暂停Swing GUI

use*_*136 0 java swing timer wait thread-sleep

海兰!所以我开始使用netbeans java 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
Run Code Online (Sandbox Code Playgroud)

我已经试过了Thread.sleep(),但在上面的例子中它等了4秒左右,然后显示整个文本(所以它没有给我我想要的拼写错误效果).

有人可以帮我这个吗?

Hov*_*els 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++;
}
Run Code Online (Sandbox Code Playgroud)

  • @ user2580136:不,相信我,你会获得更多***,并通过自己的想法和自己编写完整的示例代码来学习更多知识.然后,如果您遇到困难,请回复您的代码和问题.我给你留下了[Swing Timer教程]的链接(http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html),所以请你看一下.祝好运! (4认同)
  • @ user2580136:这是学习体验的一部分.最好学会为代码而烦恼,然后乞求代码. (2认同)