Tracking progress of multiple image downloads with SwingWorker and JProgressBar

假装没事ソ 提交于 2020-01-16 04:28:11

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/17262945/tracking-progress-of-multiple-image-downloads-with-swingworker-and-jprogressbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!