Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

java - Platform.runLater Issue - Delay Execution

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...