3
Button button = new Button("Show Text");
button.setOnAction(new EventHandler<ActionEvent>(){
    @Override
    public void handle(ActionEvent event) {
        Platform.runLater(new Runnable(){
            @Override
            public void run() {
                field.setText("START");
            }
       });

        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        Platform.runLater(new Runnable(){
            @Override
            public void run() {
                field.setText("END");
            }
        });
        }
});

After running the code above, field.setText("START") is not executed, I mean textfield did not set its text to "START", WHY? How to resolve this?

Walker
  • 307
  • 4
  • 15
  • Related: [JavaFX 8: how to add a timedelay to a listener?](http://stackoverflow.com/questions/34784037/javafx-8-how-to-add-a-timedelay-to-a-listener) and [Wait before Reacting to a Property Change JavaFX 8](http://stackoverflow.com/questions/22263008/wait-before-reacting-to-a-property-change-javafx-8) – jewelsea Jan 25 '16 at 18:27

1 Answers1

6

Keep in mind that the button's onAction is called on the JavaFX thread, therefore you are effectively halting your UI thread for 5 seconds. When the UI thread is un-frozen at the end of these five seconds both changes are applied successively, so you end up only seeing the second.

You can fix this by running all code above in a new thread:

    Button button = new Button();
    button.setOnAction(event -> {
        Thread t = new Thread(() -> {
            Platform.runLater(() -> field.setText("START"));
            try {
                Thread.sleep(5000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            Platform.runLater(() -> field.setText("END"));
        });

        t.start();
    });
Itai
  • 6,641
  • 6
  • 27
  • 51
  • 3
    good explanation of the why - though note that fx comes with extensive high-level support for animations :-) @Walker – kleopatra Jan 25 '16 at 14:00
  • 3
    The first `runLater` is unnecessary. Since the event handler runs on the application thread, `field.setText("START")` could safely be moved "outside" of the `Runnable`. – fabian Jun 13 '16 at 08:36