JavaFX: Updating UI elements in a Controller class from a Thread


Question

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

public class ViewController {
    @FXML private Label labelStatus;

    public void updateStatusLabel(String label) {
        labelStatus.setText("Status: " + label);
    }    
}

I also have a Java Thread with a run() method, like this:

public class Server extends Thread {

    public void run() {
        super.run();    
    }
}

This Server thread handles some socket connections that I need for my particular application. After a connection has been established (in the run() method -- not shown), I need to update the Label in the FXML Controller. How would I do this?

Note: I've purposely made my code and question general so it may help others with the same problem.

1
7
7/26/2013 5:28:38 AM

You call Platform.runLater(runnable) off the JavaFX UI thread to execute a runnable that updates elements of the active JavaFX Scene Graph on the JavaFX UI thread.

Also review Concurrency in JavaFX, with the Task and Service classes and see if that is not a more appropriate solution to your particular task.

For more information, see:

5
5/23/2017 10:28:05 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon