I have a concurrent task that can be in two states – active (working) and paused (via Thread.sleep(xxxx)
). When task is working indeterminate ProgressIndicator
should be visible to show user that there is a running Task
. When task is paused then ProgressIndicator
shouldn’t be shown.
This is my solution:
public class JavaFxTest7 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
var indicator = new ProgressIndicator();
indicator.setProgress(ProgressIndicator.INDETERMINATE_PROGRESS);
var vBox = new VBox(indicator);
var scene = new Scene(vBox, 300, 200);
stage.setScene(scene);
stage.show();
Task<Boolean> task = new Task<Boolean>() {
@Override
protected Boolean call() throws Exception {
while(!isCancelled()) {
this.updateValue(true);
for (long l = 1; l < 150000L; l++) {
System.out.println("Working");
}
System.out.println("Pause");
this.updateValue(false);
Thread.sleep(2500);
}
return null;
}
};
indicator.visibleProperty().bind(task.valueProperty());
new Thread(task).start();
}
}
This code works as expected and does everything I need. However, I don’t like this solution because it is not logical. I use task value to control visibility of the indicator and it is not good. I wanted to add listener to Task
state property but as I understand I can’t control state.
Is there a better solution for such problem? Maybe I should use Service
instead of Task
?