暂停 Swing GUI [英] Pausing Swing GUI

查看:54
本文介绍了暂停 Swing GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!所以我从 netbeans java gui 开发开始,我遇到了这个问题:

Hy! So I'm starting with netbeans java gui development and I have run into this problem:

我制作了一个带有按钮和文本字段的窗口.当用户单击按钮时,我希望文本字段开始输入延迟.例如:

I have made a window with a button and a text field. When the user clicks the button I want the text field to start typing itself with a delay. So for example:

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 秒左右,然后显示整个文本(所以它不会给我错字效果,我会想要).

I have already tried with Thread.sleep(), but in the example above it waits 4 seconds or so and after that displays the whole text (so it's not giving me the typo effect that I would want).

有人可以帮我解决这个问题吗?

Can somebody help me with this?

推荐答案

如果您使用 Thread.sleep(...) 或任何其他延迟 Swing 事件线程的代码,您将结束使整个 Swing 事件线程进入睡眠状态,并随之进入您的应用程序.这里的关键是改用 Swing Timer.在 Timer 的 ActionListener 的 actionPerformed 方法中,添加一个字母并增加您的索引,然后使用该索引来决定下一个添加哪个字母.

If you use Thread.sleep(...) or any other code that delays the Swing event thread, you'll end up putting the entire Swing event thread to sleep, and with it your application. The key here is to instead use a Swing Timer. In the Timer's ActionListener's actionPerformed method, add a letter and increment your index, and then use that index to decide what letter to next add.

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++;
}

这篇关于暂停 Swing GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆