2

可能重复:
JProgressBar 不会更新

所以我试图显示一个用 Java 下载的文件的下载进度。我可以将当​​前百分比作为字符串输出到控制台,但是当我尝试更新 UI 时,它会冻结,直到下载完成。

    public void downloadFile(String fileName) {
    try {
       long startTime = System.currentTimeMillis();

       System.out.println("Connecting to site...\n");

       URL url = new URL("http://assets.minecraft.net/"+fileName+"/minecraft.jar");
       URLConnection connection = url.openConnection();
        try (InputStream reader = url.openStream(); FileOutputStream writer = new FileOutputStream("minecraft.jar")) {
            byte[] buffer = new byte[153600];
            int totalBytesRead = 0;
            int bytesRead = 0;
            int totalSize = connection.getContentLength();
            jProgressBar1.setMaximum(totalSize);

            System.out.println("Downloading\n");

            while ((bytesRead = reader.read(buffer)) > 0) {  
               writer.write(buffer, 0, bytesRead);
               buffer = new byte[153600];
               totalBytesRead += bytesRead;
               jProgressBar1.setValue(totalBytesRead);
               System.out.println(totalBytesRead*100/totalSize+"% complete");
            }

            long endTime = System.currentTimeMillis();

            System.out.println("Done. " + (new Integer(totalBytesRead).toString()) + " bytes read (" + (new Long(endTime - startTime).toString()) + " millseconds).\n");
        }
    }
    catch (MalformedURLException e) {
    }
    catch (IOException e) {
    }
}

我在某处读到您需要使用另一个线程,但我无法成功地做到这一点。

4

1 回答 1

2

一种选择是使用SwingWorker。以下是您可以考虑的一些有用的答案:

于 2013-01-13T16:59:26.943 回答