banalnabutas
banalnabutas

Reputation: 13

Tracking progress of multiple image downloads with SwingWorker and JProgressBar

I'm having a hard time figuring out the right way to use SwingWorker to track multiple image downloads. I'm writing a GUI program that takes a list of image URLs as input, reads each image, and uses PDFBox to save all the images as a single PDF file. I have a downloader class with the following method:

public void downloadImagesAsPDF(URL[] urlList, String filename){
   if(urlList.length == 0)
        return;

    //build pdf
    try {
        PDDocument doc = new PDDocument();

        for(URL imgLink : urllist){
            try{
                BufferedImage bi = ImageIO.read(imgLink);
                int width = bi.getWidth();
                int height = bi.getHeight();

                PDPage page = new PDPage(new PDRectangle(width, height));
                doc.addPage(page);

                PDXObjectImage image = new PDJpeg(doc, bi);

                PDPageContentStream content = new PDPageContentStream(doc, page);
                content.drawImage(image,0,0);
                content.close();
            }
            catch(Exception e){
                System.out.println(e.getMessage());
            }
        }
        doc.save(filename + ".pdf");
    }
    catch (Exception e) { 
        System.out.println(e.getMessage());
    }}

On another class, I have a SwingWorker with a propertyChangeListener listening to it and updating a JProgressBar (rest of code is similar to ProgressBarDemo in the tutorials, except for the doInBackground method):

public Void doInBackground() {

    setProgress(0);
    URL[] URLList = {...}
    Downloader dl = new Downloader();
    dl.downloadImagesAsPDF(URLList, "some_images");  //need to track the progress inside this method.                   
    return null;
}

I want to be able to set the progress property of SwingWorker within the downloadImagesAsPDF method as the (number of bytes read * 100 / total size of the images). The only way I can think of of doing this is to pass the SwingWorker object itself as a parameter to an overridden downloadImagesAsPDF method, but it seems like a wrong design decision.

Also, is there a way to find the number of bytes read using the ImageIO.read(URL) inside the download method?? Thanks in advance!

Upvotes: 1

Views: 778

Answers (1)

trashgod
trashgod

Reputation: 205875

You have considerable flexibility with SwingWorker; there's no need to let it dictate your design. In this example, a loosely coupled PropertyChangeListener receives notifications generated indirectly by the worker's call to setProgress(). In this example, each worker holds a reference to a component JLabel for recording progress directly, while a supervisor thread awaits a CountDownLatch.

Upvotes: 2

Related Questions