Platform.runLater Issue - Delay Execution

2019-01-15 22:02发布

问题:

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?

回答1:

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();
    });