所以我正在试着做一个下载程序,用进度条显示下载的进度。但是我遇到了问题,因为它实际上并没有更新进度条。基本上,当它应该是蓝色时,它仍然是白色的。如果有人能提供帮助,代码在下面。
JProgressBar progressBar = new JProgressBar(0, ia);
con.add(progressBar, BorderLayout.PAGE_START);
con.validate();
con.repaint();
progressBar = new JProgressBar(0, ia);
progressBar.setValue(0);
System.out.print("Downloading Files");
while ((count = in.read(data, 0, downloadSpeed)) != -1){
fout.write(data, 0, count);
if (count >= 2){
progressBar.setString("Downloading : " + ia + " @ " + count + "Kbs per second");
} else {
progressBar.setString("Downloading : " + ia + " @ " + count + "Kb per second");
}
progressBar.setValue(count);
con.add(progressBar, BorderLayout.PAGE_START);
try{
Thread.sleep(1000);
} catch (Exception e){}
}发布于 2012-08-19 02:01:57
使用与SwingWorker的组合。请看这里的示例:SwingWorker and Progress Bar
@气垫船:你说得对。请允许我参考相应的SwingWorker page of JavaDoc,在我看来这最好地解释了这种情况。
发布于 2012-08-19 04:22:58
正如@happyburnout指出的那样,你最好在一个单独的线程中处理你的下载,使用SwingWorker可能是你正在做的最好的解决方案。
主要原因是您阻塞了Event Dispatching Thread (AKA EDT)的运行,阻止了任何重绘请求(以及其他重要的UI内容)被处理。
你应该通读一遍
现在,这几乎直接取自API文档,但给出了一个带有JProgressBar的SwingWoker的基本概念。
“工人”。
public class Worker extends SwingWorker<Object, Object> {
@Override
protected Object doInBackground() throws Exception {
// The download code would go here...
for (int index = 0; index < 1000; index++) {
int progress = Math.round(((float)index / 1000f) * 100f);
setProgress(progress);
Thread.sleep(10);
}
// You could return the down load file if you wanted...
return null;
}“进度窗格”
public class ProgressPane extends JPanel {
private JProgressBar progressBar;
public ProgressPane() {
setLayout(new GridBagLayout());
progressBar = new JProgressBar();
add(progressBar);
}
public void doWork() {
Worker worker = new Worker();
worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
progressBar.setValue((Integer) evt.getNewValue());
}
}
});
worker.execute();
}
}记住摇摆的黄金法则
除了EDT
Thread,Thread更新UI组件。Thread使用Swing,您将拥有一段轻松愉快的时光:D
https://stackoverflow.com/questions/12020949
复制相似问题