java - 使用 swing GUI 在下载文件时显示进度条

标签 java swing download progress-bar progress

我目前有一个类,它应该在下载文件时向我显示一个简单的表单。它正在工作,但进度条没有更新,只有下载完成后我才能看到它。有人可以帮助我吗?

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);
        }
    }
}

最佳答案

您的问题是一个经典的 Swing 并发问题。解决方案一如既往——在后台线程中执行长时间运行的代码,例如可以通过 SwingWorker 找到的代码。

例如,

import java.awt.FlowLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

import javax.swing.JFrame;
import javax.swing.SwingWorker;

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();
      final 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);
      final Worker worker = new Worker(site, file);
      worker.addPropertyChangeListener(new PropertyChangeListener() {

         @Override
         public void propertyChange(PropertyChangeEvent pcEvt) {
            if ("progress".equals(pcEvt.getPropertyName())) {
               current.setValue((Integer) pcEvt.getNewValue());
            } else if (pcEvt.getNewValue() == SwingWorker.StateValue.DONE) {
               try {
                  worker.get();
               } catch (InterruptedException | ExecutionException e) {
                  // handle any errors here
                  e.printStackTrace(); 
               }
            }

         }
      });
      worker.execute();
   }
}

class Worker extends SwingWorker<Void, Void> {
   private String site;
   private File file;

   public Worker(String site, File file) {
      this.site = site;
      this.file = file;
   }

   @Override
   protected Void doInBackground() throws Exception {
      URL url = new URL(site);
      HttpURLConnection connection = (HttpURLConnection) url
            .openConnection();
      int filesize = connection.getContentLength();
      int 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);
               int percent = (totalDataRead * 100) / filesize;
               setProgress(percent);
            }
         }
      }
      return null;
   }
}

关于java - 使用 swing GUI 在下载文件时显示进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21954581/

相关文章:

java - JCombobox不显示

javascript - 使用 Python 通过 Javascript URL 自动下载文件

.net - 在ASP.net MVC2中解析 “this operation requires IIS integration pipeline mode”

Java JTable - 只使一列可编辑

java - Spring JPA - 将外键映射为主键 [MySQL]

java - SpringMVC源码的区别

java - 使用 JComboBox 过滤 JTable 会生成 ArrayIndexOutOfBoundsException

Java JFrame 对话框问题

html - Chrome 扩展 : Download/export content created "on the fly"

java - AWS Lambda + SQS(Java)。 Lambda 成功完成工作,但未从 SQS 中删除消息。是否应该再次发送此消息进行处理?