0

I am working with JavaFX and I need to somehow update a UI element from a worker thread.

My worker thread is constantly listening, through a socket, for incoming connections. When it detects one, it calls a method updateListOfConnections();

What I want to do is updateListOfConnections is pretty simple:

this.deviceList.clear();
this.deviceList.addAll(this.contactManager.getContacts().keySet());

if(this.deviceList.size() > 0){
    updateConnectButtonState(false);
} else {
    updateConnectButtonState(true);
}

As you can see, I affect the state of the UI for a couple items here and when I attempt to call updateListOfConnections from my thread, I get an exception.


Some possible solutions that I came up with (which are really unideal) are:

I simply have the user manually refresh the deviceList by invoking updateListOfConnections with the press of a button.

Or, have a loop constantly running and when it gets to a certain interval, reset the interval and invoke updateListOfConnections.


So my main question is how do I update an UI element from a worker thread in Java with JavaFX?

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
waylonion
  • 6,866
  • 8
  • 51
  • 92

2 Answers2

2

Use the Platform#runLater() static method, which runs the specified Runnable on the JavaFX Application Thread; it could be called from any thread:

Platform.runLater(() -> {
    // The code that you want to run on the JavaFX Application Thread
});
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
0

You can use Platform.runLater(Runnable) to execute code on the main JavaFX thread.

I would however advise you to take a look at JavaFX binding. LINK

For instance, in your controller (instantiated from FXML for instance)

@FXML private Button aButton;
private final BooleanProperty disableProperty = new ReadOnlyBooleanWrapper();

public init() {
    disableProperty.bind(-- Your observable list here--.isEmpty());
    aButton.disableProperty().bindBidirectional(disableProperty);
Robin Jonsson
  • 2,761
  • 3
  • 22
  • 42
  • What if the socket connection was successful, and it deliberately returned zero contacts? – VGR Feb 19 '16 at 15:28
  • @VGR Any updates made to the list you're binding to are reflected in the view automatically. That's the idea of JavaFX bindings. – Robin Jonsson Feb 19 '16 at 21:01
  • What I meant was that an empty list doesn't necessarily indicate the lack of a connection. – VGR Feb 19 '16 at 23:23