【问题标题】:Pausing Swing GUI暂停 Swing GUI
【发布时间】:2014-04-11 22:38:57
【问题描述】:

喂! 所以我从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 秒左右,然后显示整个文本(所以它没有给我想要的错字效果)。

有人可以帮我吗?

【问题讨论】:

标签: java swing timer wait thread-sleep


【解决方案1】:

如果您使用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++;
}

【讨论】:

  • 您能否写一个适合我的示例的完整代码示例?我真的很感激。
  • @user2580136:不,相信我,通过使用我的想法并自己编写完整的示例代码,您将获得很多更多信息并了解更多信息.然后,如果您遇到困难,请返回您的代码和您的问题。我给你留下了Swing Timer Tutorial 的链接,所以也请看一下。祝你好运!
  • 我会尝试,但我担心我会流下很多眼泪:/
  • @user2580136:这都是学习体验的一部分。最好学会为代码流汗而不是乞求代码。
  • @user2580136:不,继续努力,你会得到它!
【解决方案2】:

使用类似这样的东西让它工作:

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()

有没有人知道一个更简单但效果相同的方法?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    相关资源
    最近更新 更多