有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java下载时如何解决JavaFXProgressIndicator重绘问题?

我正在用这个循环从ftp客户端下载文件

private void download(String date){
    try {
        FTPFile ftpFile = client.mlistFile(filename());
        long ftpFileSize = ftpFile.getSize();
        frame.setMaximumProgress((int) ftpFileSize);
        File downloadFile = new File(folder + filename());
        OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile));
        InputStream inputStream = client.retrieveFileStream(fileName);
        byte[] bytesArray = new byte[4096];
        int bytesRead = -1;
        int bytes = 0;
        while ((bytesRead = inputStream.read(bytesArray)) != -1){
            outputStream2.write(bytesArray, 0, bytesRead);
            bytes += bytesRead;
        }
        if (client.completePendingCommand()){
            outputStream2.close();
            inputStream.close();
        } else{
            JOptionPane.showMessageDialog(null, "Downloading error.");
        }
    } catch (IOException e) {
        if(e instanceof FTPConnectionClosedException){
            reconnect();
        }
    }
}

前进指示器仍然在一个位置上。 方法setProgress成功启动该进度

public void setProgress(double value){
    System.out.println(value);
    progress.setProgress(value);
}

共 (1) 个答案

  1. # 1 楼答案

    只需按原意使用Task Class,无需重新发明轮子

    public class DownloadTask extends Task<Void> {
      public Void call() {
        while ((bytesRead = inputStream.read(bytesArray)) != -1){
          outputStream2.write(bytesArray, 0, bytesRead);
          bytes += bytesRead;
          updateProgress(bytes, ftpFileSize);
        }
      }
    }
    

    并将{}的{}绑定到{}的{}上

    有关如何绑定这两个属性的示例:

    ProgressIndicator progress = new ProgressIndicator();
    DownloadTask task = new DownloadTask();
    progress.progressProperty().bind(task.progressProperty());
    new Thread(task).start();