Md. Shougat Hossain
Md. Shougat Hossain

Reputation: 521

Background service and service monitoring in javafx

I am developing a javafx project for uploading image file to a aws s3 bucket. Before uploading the images I check the validity of images like height, weight and size of the images. As the uploading process is time consuming, I create a monitor to monitor (screen) the uploading progress.

class Monitor extends Stage {
private TextArea textArea = new TextArea();
    Monitor(){
        this.setTitle("Image Uploading Monitor");
        this.getIcons().add(new Image("/rok.png"));
        this.setFullScreen(false);
        this.setResizable(false);
        this.textArea.setEditable(false);
        this.textArea.setPrefSize(700, 450);
        Pane pane = new Pane();
        pane.getChildren().add(this.textArea);
        Scene scene = new Scene(pane, 700, 450);
        this.setScene(scene);
    }

    void print(String string) {
        this.textArea.appendText(string);
        this.textArea.selectPositionCaret(textArea.getLength());
    }
}

Then after every image uploading I want to print a message in the monitor

for (File image : images) {
   uploadFileToS3Bucket(image, "uploadingLocation");
   monitor.print("Uploading image"+image.getName()+"\n");
}

The code is working fine, but the problem is, the monitor show the output after all images uploading.

Because I run hole project in a single thread. How can I use multi thread to solve the problem?

Upvotes: 0

Views: 235

Answers (1)

James_D
James_D

Reputation: 209653

Put the code to upload the images in a background thread, and schedule the call to monitor.print(..) on the FX Application Thread:

new Thread(() -> {
    for (File image : images) {
       uploadFileToS3Bucket(image, "uploadingLocation");
       Platform.runLater(() -> monitor.print("Uploading image"+image.getName()+"\n"));
    }
}).start();

This assumes your uploadFileToS3Bucket() method performs no UI work.

Upvotes: 1

Related Questions