1

I want to make a pause after an event. But when I use Thread.Sleep(1000), it also stops the code above. For example:

attackButton.setOnAction(e -> {
        int playerAttack = player.getAtt();
        mob.setHP(playerAttack);
        mobHPLabel.setText(mob.getHP() + " HP");
        eventTextArea.appendText("You dealt " + playerAttack + " damage to the " + mob.getEntityClass() + "\n");
        Layout.setTextAreaFont(eventTextArea, "black", 15);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        mobTurn();
    });

This is just a small part of my code, but the problem is here. The "Thread.sleep(1000)" doesn't only delay 'mobTurn()' which it's supposed to do. It also stop the code above, "event.TextArea.appendText(..."

  • 2
    I suppose you actually suspend the UI thread which is responsible for making the appended text visible *after* your action handler is finished. Consequently, you should never pause this thread. You could start another thread which waits 1000 seconds and executes `mobTurn()` then. – Michael Hoff Dec 12 '16 at 21:47
  • I recommend following Tomas Mikula's answer in the dup question. Using the animation API avoids using the resources associated with a background thread. – James_D Dec 12 '16 at 22:41
  • You might wish to disable the attack button until the mobTurn completes, otherwise the player could mash the attack button before the mob gets a chance to take a turn, which hardly seems fair :-) – jewelsea Dec 13 '16 at 01:09
  • Replacing the sleep call with a [PauseTransition](http://stackoverflow.com/questions/34784037/javafx-8-how-to-add-a-timedelay-to-a-listener) for the `mobTurn()` would also work here. – jewelsea Dec 13 '16 at 01:10

1 Answers1

1

By calling Thread.sleep(..) in an event handler you actually pause your core UI thread. That is why not only mobTurn() is delayed, but also your complete UI. That includes invalidation and drawing of your interface, as well as handling of other events. You will perceive your application as 'frozen' or 'not responding' in that time.

Instead, you should start another thread which in turn waits and executes your desired action when the time has come. You could use Platform.runLater(..) for this. See this answer for an example.

Community
  • 1
  • 1
Michael Hoff
  • 6,119
  • 1
  • 14
  • 38