It would rather be a very simple concept, but since I am totally new to concurrency in JavaFX. I have been struggling to understand this concept.
While building a very simple JavaFX application, I wanted to perform some lengthy task in background and keep the UI safe from freezing.
In the example below, I am trying to create a simple background task service and then use ControlsFX Dialog to show progress bar over the main UI window.
However, I wanted to know how can I give some input arguments to this service and get a boolean output from it. This is really simple to do in C# BackgroundWorker, but still couldn't figure out in JavaFX. Any hints would be a great help.
Tried this simple example
public void runTask(Stage stage) throws URISyntaxException, IOException {
Service<Void> service = new Service<Void>() {
@Override
protected Task<Void> createTask() {
return new Task<Void>() {
@Override
protected Void call() throws InterruptedException, URISyntaxException, IOException {
// some time consuming task here
// use the input arguments and perform some action on it
// then set the process result to a Boolean and return after the task is completed
// also keep hold back any other process to from executing on UI
return null;
}
};
}
};
Dialogs.create()
.owner(stage)
.title("Performing Task!")
.masthead("Please wait...")
.showWorkerProgress(service);
service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
System.out.println("done:" + event.getSource().getValue());
}
});
service.setOnFailed(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
throw new UnsupportedOperationException("Failed."); //To change body of generated methods, choose Tools | Templates.
}
});
service.setOnCancelled(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
throw new CancellationException("Cancelled."); //To change body of generated methods, choose Tools | Templates.
}
});
service.start();
}