JavaFX: updating user interface elements in a Controller class from a thread

In JavaFX, I have a Controller class that extracts control components from an FXML file and has methods that act on the component shown here with a label:

public class ViewController { @FXML private Label labelStatus; public void updateStatusLabel(String label) { labelStatus.setText("Status: " + label); } } 

I also have a Java thread with the run () method, for example:

 public class Server extends Thread { public void run() { super.run(); } } 

This server thread handles some socket connections that I need for my specific application. After the connection is established (not shown in the run () method) I need to update the Label in the FXML controller. How can I do it?

Note. I intentionally made my code and general question so that it could help others with the same problem.

+6
source share
1 answer

You call Platform.runLater (runnable) from the JavaFX user interface thread to run runnable, which updates the active graph elements of the JavaFX scene to the JavaFX UI thread.

Also check out Concurrency in JavaFX , with Task and Service, and see if this is a more suitable solution for your specific task.

For more information see

+4
source

Source: https://habr.com/ru/post/950326/


All Articles