2

Possible Duplicate:
JProgressBar wont update

So I am trying to show the download progress of a file being downloaded in Java. I can output the current percentage as a String to the console, but when I try to update the UI, it freezes until the download is complete.

    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) {
    }
}

I read somewhere that you need to use another thread but I was unable to successfully do that.

Community
  • 1
  • 1
AKrush95
  • 1,381
  • 6
  • 18
  • 35

1 Answers1

2

One option would be using SwingWorker. Here are some useful answers you may consider:

Community
  • 1
  • 1
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417