在执行下载过程时,为什么我的JFrame是空白的? [英] Why is my JFrame blank while I do a download process?
问题描述
我有一个extends JFrame
的类,并且在其中有如下方法:
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();
}
}
此方法下载文件并获取下载百分比.在运行时,我的JFrame是空白的.它运行后,JFrame会更新并正确显示,但是我希望它经常更新(好吧,首先显示自身),我该怎么做?
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?
推荐答案
您应使用 SwingWorker类以实现下载任务.主线程上长时间运行的任务会冻结GUI,直到任务完成为止,这就是为什么这些任务应在后台线程上执行的原因. SwingWorker类将允许您执行此操作并同时更新您的进度条.
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.
这篇关于在执行下载过程时,为什么我的JFrame是空白的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!