Java Swing: changing text after delay
Basically, I have this game. Once I guess the correct answer, it starts a new game of new words I want to display correctly! But after three seconds, change it to an empty string What do I do?
My attempt:
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!");
}
Edit:
My solution
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!");
}
}
I'm not sure, but I hope I follow mad programmer's advice instead of blocking the event itself, but a new thread I also look for Java timer
Solution
Swing is an event - driven environment When an event scheduling thread is blocked, no new events can be processed
You should never block EDT in any time-consuming process (such as I / O, loop, or thread #sleep)
You may want to read the event dispatch thread for more information
Instead, you should use javax swing. Timer. It will trigger actionlistener after a given delay
The advantage is that the actionperformed method is executed in the context of event dispatching thread
For examples, see this or this or this or this
