Reputation: 41
I am attempting to bind a progress bar to the progress of a service. I have created the progress bar in scene builder, and have attempted the below code. But the progress bar continually runs, and does not represent the service it is connected to. It should be running while the service is running, and representing the data being downloaded. How do I bind the progress bar to represent the service I have created.
@FXML
private ProgressBar ProgressBar;
service.start();
ProgressBar.progressProperty().bind(service.workDoneProperty());
Upvotes: 1
Views: 6501
Reputation: 36722
You should bind ProgressBar's progressProperty()
to Service's progressProperty()
and not to its workDoneProperty i.e.
import javafx.application.Application;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
ProgressBar progressBar = new ProgressBar();
StackPane root = new StackPane(progressBar);
Scene scene = new Scene(root, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
Service service = new Service() {
@Override
protected Task createTask() {
return new Task() {
@Override
protected Object call() throws Exception {
for(int i=0; i<100; i++){
updateProgress(i, 100);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
};
}
};
progressBar.progressProperty().bind(service.progressProperty());
service.start();
}
public static void main(String[] args) {
Application.launch(args);
}
}
Upvotes: 5