JavaFX2: Can I pause a background Task / Service?

Solution 1:

Solution

When your background process encounters a situation where it requires a user to be prompted for input, use FutureTask executed in Platform.runLater to showAndWait the dialog prompt on the JavaFX application thread. In the background process use futureTask.get to pause the background process until the user has input the necessary values which will allow the process to continue.


Sample Code Snippet

Here is the essence of code for this approach which can be placed inside the call method of your background process:

String nextText = readLineFromSource();
if ("MISSING".equals(nextText)) {
  updateMessage("Prompting for missing text");
  FutureTask<String> futureTask = new FutureTask(
    new MissingTextPrompt()
  );
  Platform.runLater(futureTask);
  nextText = futureTask.get();
}
...
class MissingTextPrompt implements Callable<String> {
  private TextField textField;

  @Override public String call() throws Exception {
    final Stage dialog = new Stage();
    dialog.setScene(createDialogScene());
    dialog.showAndWait();
    return textField.getText();
  }
  ...
}

Sample Application

I created a small, complete sample application to demonstrate this approach.

The output of the sample application is:

promptingtaskdemooutput

Sample Output Explanation

Lines read without missing values are just plain brown. Lines with a prompt value entered have a pale green background. Fourteen lines have been read, the background task has already paused once at the 6th line which was missing a value. The user was prompted for the missing value (to which the user entered xyzzy), then the process continued until line 14 which is also missing and the background task is again paused and another prompt dialog is being displayed.