问题
I have a class that extends JFrame
and inside it I have a method as follows:
public void downloadUrl(String filename, String urlString) throws MalformedURLException, IOException
{
BufferedInputStream in = null;
FileOutputStream fout = null;
try
{
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename);
byte data[] = new byte[1024];
int count;
int modPackSize = getModPackSize();
while ((count = in.read(data, 0, 1024)) != -1)
{
fout.write(data, 0, count);
downloadedPerc += (count*1.0/modPackSize)*100;
progressBar.setValue((int) downloadedPerc);
label.setText((int) downloadedPerc + "%");
System.out.println(downloadedPerc);
}
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if (in != null)
in.close();
if (fout != null)
fout.flush();
fout.close();
}
}
This method downloads the file and gets the downloaded percentage. While this is running, my JFrame is blank. After it runs, the JFrame updates and shows correctly, but I would want it to update(well, first show itself) often, how could I do that?
回答1:
You should use the SwingWorker class to implement the downloading task. Long-running tasks on the main thread freeze your GUI until the task is finished, this is why these tasks should be executed on a background thread. The SwingWorker class will allow you to do this and simultaneously update your progress bar.
来源:https://stackoverflow.com/questions/12347928/why-is-my-jframe-blank-while-i-do-a-download-process