【发布时间】:2014-02-22 12:51:06
【问题描述】:
我目前有一门课,它应该在下载文件时向我展示一个简单的表单。它正在工作,但进度条没有更新,我只能在下载完成后才能看到它。有人可以帮我吗?
import java.awt.FlowLayout;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JProgressBar;
public class Downloader {
public Downloader(String site, File file) {
JFrame frm = new JFrame();
JProgressBar current = new JProgressBar(0, 100);
current.setSize(50, 100);
current.setValue(0);
current.setStringPainted(true);
frm.add(current);
frm.setVisible(true);
frm.setLayout(new FlowLayout());
frm.setSize(50, 100);
frm.setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
URL url = new URL(site);
HttpURLConnection connection
= (HttpURLConnection) url.openConnection();
int filesize = connection.getContentLength();
float totalDataRead = 0;
try (java.io.BufferedInputStream in = new java.io.BufferedInputStream(connection.getInputStream())) {
java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
try (java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024)) {
byte[] data = new byte[1024];
int i;
while ((i = in.read(data, 0, 1024)) >= 0) {
totalDataRead = totalDataRead + i;
bout.write(data, 0, i);
float Percent = (totalDataRead * 100) / filesize;
current.setValue((int) Percent);
}
}
}
} catch (IOException e) {
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null, e.getMessage(), "Error",
javax.swing.JOptionPane.DEFAULT_OPTION);
}
}
}
【问题讨论】:
-
不要阻塞 EDT(事件调度线程)——当这种情况发生时,GUI 将“冻结”。而是为长时间运行的任务实现
SwingWorker。有关详细信息,请参阅Concurrency in Swing。 -
还有第三个:My JProgressBar is not Updating Until it is 100%。是时候提高您的 Google 技能了! ;)
-
谢谢大家,现在可以使用了。我一直在寻找,但没有找到适合我想要实现的目标。谢谢!
标签: java swing download progress-bar progress