简体   繁体   English

如何添加进度条以显示Java中的下载状态?

[英]How to add progressbar to display download status in Java?

I am using an external library to download files from Mega but I need a progressbar to display the duration of the download to the user. 我正在使用外部库从Mega下载文件,但是我需要一个进度条来向用户显示下载持续时间。 I have read a lot of progressbar related articles on stackoverflow but the problem is that I don't know what take so long in my code to add a progress bar. 我已经阅读了很多关于stackoverflow的与Progressbar相关的文章,但是问题是我不知道花多长时间才能添加进度条。

Where and how do I have to add a progressbar to display the download status? 我必须在哪里以及如何添加进度条以显示下载状态?

    try {

        URLConnection urlConn = new URL(file_url).openConnection();
        print(file_url);
        is = urlConn.getInputStream();
        while ((read = is.read(buffer)) > 0) {
            cos.write(buffer, 0, read);
        }
    } finally {
        try {
            cos.close();
            if (is != null) {
                is.close();
            }
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }
    print("Download finished");
}

You can build a progress bar dialog and preventively show it, and then delegate your costly behind-the-scenes download process to a SwingWorker . 您可以构建进度条对话框并预防性地显示它,然后将昂贵的幕后下载过程委派给SwingWorker

The SwingWorker is a kind of Runnable object (it will be executed behind your main thread) and it is specially conceived to update graphic elements ( publish changes to them) as it does its work. SwingWorker是一种Runnable对象(它将在您的主线程后面执行),并且在执行其工作时专门构思为更新图形元素( publish更改publish给它们)。

Have a look at this stackoverflow question: 看一下这个stackoverflow问题:

SwingWorker ProgressBar SwingWorker进度栏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM