暂停Swing GUI

时间:2014-04-11 22:38:58

标签: java swing timer wait thread-sleep

HY! 所以我开始使用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

我已经尝试过使用Thread.sleep(),但是在上面的示例中它会等待4秒左右,之后会显示整个文本(所以它不会给我我想要的拼写错误效果)。

有人可以帮我吗?

2 个答案:

答案 0 :(得分: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++;
}

答案 1 :(得分: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()

有人知道一个更简单的方法可能有相同的效果吗?