Friday, June 8, 2012

Update UI in JavaFX Application Thread using Platform.runLater()

Last exercise show how to do something in background thread using ExecutorService. The code update UI element(textCounter) in background thread. It's not a good practice to do so, may be it cannot run on some OS!

It's a easy approach to solve it with javafx.application.Platform class. The method Platform.runLater(java.lang.Runnable runnable) run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future. You can also call Platform.isFxApplicationThread() to check if the calling thread is the JavaFX Application Thread.

Update UI in JavaFX Application Thread using Platform.runLater()


package javafx.ex;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class testScheduledExecutorService extends Application {
    
    Text textCounter;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Start ScheduledExecutorService");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                startScheduledExecutorService();
            }
        });
        
        textCounter = new Text();
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(btn, textCounter);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    private void startScheduledExecutorService(){

        final ScheduledExecutorService scheduler 
            = Executors.newScheduledThreadPool(1);

        scheduler.scheduleAtFixedRate(
                new Runnable(){
                     
                    int counter = 0;
                     
                    @Override
                    public void run() {
                        counter++;
                        if(counter<=10){
                            
                            Platform.runLater(new Runnable(){
                                @Override
                                public void run() {
                                    textCounter.setText(
                                    "isFxApplicationThread: " 
                                    + Platform.isFxApplicationThread() + "\n"
                                    + "Counting: "
                                    + String.valueOf(counter));
                                }
                            });
                            
                            
                        }else{
                            scheduler.shutdown();
                            Platform.runLater(new Runnable(){
                                @Override
                                public void run() {
                                    textCounter.setText(
                                    "isFxApplicationThread: " 
                                    + Platform.isFxApplicationThread() + "\n"
                                    + "-Finished-");
                                }
                            });
                        }
                         
                    }
                }, 
                1, 
                1, 
                TimeUnit.SECONDS);      
    }
}



5 comments:

  1. Nice tutorials, thanks java-buddy. By the way, is it possible for creating a semaphore object with wait and notify that actually work in javafx 2.0 ?

    ReplyDelete
  2. Thank you man! That was quick and useful

    ReplyDelete
  3. Hy !
    This is a really nice tutorial. :)
    I am working on a javafx game application and I'm stuck at the point of making the gameplay part. I can't get it working. If I try to run it on a separate thread the game freezes.
    I was wondering if you could help me out with some infos.
    We could get in touch on google+.
    Thanx in advice. :)

    ReplyDelete
  4. Platform.runLater() makes my UI slow . Any solution?

    ReplyDelete