1

I guess this has been covered before, but I did not find an answer that really solved my problem. In this code excerpt, I want to display a reaction to a button click (set text in lblMessage), wait for a second, then display another image.

In the section marked as "wait 1000 ms" I have tried Thread.sleep(), as well as calculating the elapsed system time. However, in both cases lblMessage is only filled AFTER the wait time.

I came across Timer, but I cannot figure out the syntax how to use it (especially the task that needs to be entered).

Thanks in advance for your help!

public void answerButtonClicked(ActionEvent event) {

    endTime = System.nanoTime();
    elapsedTime = (endTime - startTime);
    String answerTime = String.format("%.2f", (elapsedTime/1000000000));

    Button btnAnswer = (Button)event.getSource();
    String answer = btnAnswer.getId();      
    String correctAnswer = mpScenes.get(model.getNextScene(round-1));

    if (answer.equals(correctAnswer)) {
        lblMessage.setText("Richtig (" + answerTime + "s)");
    } else {
        lblMessage.setText("Falsch (" + answerTime + "s)");
    }

    **--<wait 1000 ms>--**

    if (round < numberOfRounds) {
        round++;
        setNewMainImage(round);
    } else {
        endOfGame();
    }
}
Cord
  • 45
  • 1
  • 6

1 Answers1

1

Replace your **--<wait 1000 ms>--** with something like this:

Timer timer = new Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (round < numberOfRounds) {
            round++;
            setNewMainImage(round);
        } else {
            endOfGame();
        }

    }
});

timer.start();

javax.swing.Timer allows you to delay some action that will be executed later in the swing UI dispatch thread.

spi
  • 1,673
  • 13
  • 19