Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 630
Tarif Haque Avatar asked Jul 26 '13 05:07

Tarif Haque


1 Answers

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:

  • Usage of JavaFX Platform.runLater and access to UI from a different thread.
  • Platform.runLater and Task in JavaFX
  • JavaFx response to SwingUtilities.invokeLater
like image 136
jewelsea Avatar answered Oct 20 '22 07:10

jewelsea