10

So I am aware that JavaFx's method of updating the GUI while using a thread is called Task but does the code work in similar way or are there any differences. let me give you a swing example:

Another class outside the GUI that runs as a thread

public void run(){
    while (socket.isConnected()) {
        String x = input.next();
        System.out.println(x);
        mg.updateChat(x)
    }
}

Inside the actual GUI

public void updateChat(final String input){
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            txtChat.setText(input); 
        }
    }); 
}

Does Task work the exact same way? Or are there differences and if there are how would you modify this code to work in a JavaFx project?

Josiah Yoder
  • 3,321
  • 4
  • 40
  • 58
Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364

1 Answers1

17

Are you looking for SwingUtil.invokeLater counterparts in JavaFX. If yes, it is:

Platform.runLater(java.lang.Runnable runnable)
amru
  • 1,388
  • 11
  • 14
  • As far as I can understand [the api]( http://docs.oracle.com/javafx/2/api/javafx/application/Platform.html), yes. I use it to update javafx ui controls in multithreaded environment just like I use SwingUtilities.invokeLater for Swing controls. – amru Oct 20 '12 at 14:45
  • No luck here, my UI freezes when I'm doing runLater. – Ali Feb 03 '13 at 16:26
  • Make sure your long running task is running inside a Task and that whenever you need to update the ui you call Platform.runLater. Do not run long running tasks inside runLater because your UI will then freeze. – mario May 27 '17 at 02:25
  • 4
    The lambda version is nice Platform.runLater(() -> txtChat.setText(input)) – Wolfgang Fahl Jun 26 '17 at 12:25