I try to run in JavaFX application background thread periodically, which modifies some GUI property.
I think I know how to use Task
and Service
You can use ScheduledService too. I am using this alternative after noticing that during the use of Timeline
and PauseTransition
occurred some UI freezes in my application, especially when the user interacts with the elements of a MenuBar
(on JavaFX 12). Using the ScheduledService
these problems no longer occurred.
class UpdateLabel extends ScheduledService {
private Label label;
public UpdateLabel(Label label){
this.label = label;
}
@Override
protected Task createTask(){
return new Task(){
@Override
protected Void call(){
Platform.runLater(() -> {
/* Modify you GUI properties... */
label.setText(new Random().toString());
});
return null;
}
}
}
}
And then, use it:
class WindowController implements Initializable {
private @FXML Label randomNumber;
@Override
public void initialize(URL u, ResourceBundle res){
var service = new UpdateLabel(randomNumber);
service.setPeriod(Duration.seconds(2)); // The interval between executions.
service.play()
}
}