问题
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.
回答1:
One option would be using SwingWorker. Here are some useful answers you may consider:
- Need to have JProgress bar to measure progress when copying directories and files
- How SwingWorker works
来源:https://stackoverflow.com/questions/14305747/progress-bar-freezing-while-downloading-file-in-java