JavaFx response to SwingUtilities.invokeLater
Asked Answered
E

1

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?

Enthrone answered 20/10, 2012 at 0:55 Comment(0)
S
17

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

Platform.runLater(java.lang.Runnable runnable)
Sapers answered 20/10, 2012 at 3:58 Comment(4)
As far as I can understand [the api]( 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.Sapers
No luck here, my UI freezes when I'm doing runLater.Unscrew
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.Riggins
The lambda version is nice Platform.runLater(() -> txtChat.setText(input))Cymric

© 2022 - 2024 — McMap. All rights reserved.