Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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 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.

like image 577
Raza Avatar asked Feb 19 '23 05:02

Raza


1 Answers

Swing is an event driven environment. While you block the Event Dispatching Thread, no new events can be processed.

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.

Instead, you should use a javax.swing.Timer. It will trigger a ActionListener after a given delay.

The benefit of which is that the actionPerformed method is executed with the context of the Event Dispatching Thread.

Check out this or this or this or this for an examples

like image 56
MadProgrammer Avatar answered Feb 26 '23 23:02

MadProgrammer