Java Swing:延迟后更改文本 [英] Java Swing: Change Text after delay
问题描述
基本上,我有这个游戏,一旦猜到了正确的答案,它开始一个新单词的新游戏。我想显示正确!
但三秒后,将其更改为空字符串。我该怎么做?
Basically, I have this game where once guesses the correct answer it starts a new game with a new word. I want to display Correct!
but after three seconds, change it to a empty string. How do I do that?
我的尝试:
if (anagram.isCorrect(userInput.getText()))
{
anagram = new Anagram();
answer.setText("CORRECT!");
word.setText(anagram.getRandomScrambledWord());
this.repaint();
try
{
Thread.currentThread().sleep(3000);
}
catch (Exception e)
{
}
answer.setText("");
} else
{
answer.setForeground(Color.pink);
answer.setText("INCORRECT!");
}
修改:
我的解决方案:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
if (anagram.isCorrect(userInput.getText()))
{
answer.setText("CORRECT!");
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
anagram = new Anagram();
word.setText(anagram.getRandomScrambledWord());
answer.setText("");
userInput.setText("");
}
};
Timer timer = new Timer(3000, taskPerformer);
timer.setRepeats(false);
timer.start();
} else
{
answer.setForeground(Color.pink);
answer.setText("INCORRECT!");
}
}
我不确定,但我希望我是遵循MadProgrammer的建议而不是阻止事件本身,而是新线程。我也会查找Java Timer。
I am not sure, but I hope that I am following MadProgrammer's advice and not blocking the event itself, but the new thread. I will look up Java Timer also.
推荐答案
Swing是一个事件驱动的环境。当您阻止事件调度线程时,不能处理任何新事件。
Swing is an event driven environment. While you block the Event Dispatching Thread, no new events can be processed.
您永远不应该在任何耗时的过程中阻止EDT(例如I / O,循环或线程#sleep
例如)。
You should never block the EDT with any time consuming process (such as I/O, loops or Thread#sleep
for example).
您可能希望通读事件调度线程了解更多信息。
You might like to have a read through The Event Dispatch Thread for more information.
相反,您应该使用 javax.swing.Timer
。在给定的延迟后它会触发 ActionListener
。
Instead, you should use a javax.swing.Timer
. It will trigger a ActionListener
after a given delay.
其好处是 actionPerformed
方法使用事件调度线程的上下文执行。
The benefit of which is that the actionPerformed
method is executed with the context of the Event Dispatching Thread.
这篇关于Java Swing:延迟后更改文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!