我寫了一段代碼,用於從互聯網下載文件(在後臺服務中),並在彈出的階段顯示下載進度。代碼編譯成功,沒有運行時錯誤。然而,沒有下載發生,並且進度指示器保持不確定。進度指示器保持不確定狀態,沒有下載
該代碼是爲了說明我的觀點而定製的。請看看它,讓我明白我出錯的地方。
謝謝!
public class ExampleService extends Application {
URL url;
Stage stage;
public void start(Stage stage)
{
this.stage = stage;
stage.setTitle("Hello World!");
stage.setScene(new Scene(new StackPane(addButton()), 400, 200));
stage.show();
}
private Button addButton()
{
Button downloadButton = new Button("Download");
downloadButton.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent e)
{
FileChooser fileSaver = new FileChooser();
fileSaver.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF", "pdf"));
File file = fileSaver.showSaveDialog(stage);
getDownloadService(file).start();
}
});
return downloadButton;
}
private Service getDownloadService(File file)
{
Service downloadService = new Service()
{
protected Task createTask()
{
return doDownload(file);
}
};
return downloadService;
}
private Task doDownload(File file)
{
Task downloadTask = new Task<Void>()
{
protected Void call() throws Exception
{
url = new URL("http://www.daoudisamir.com/references/vs_ebooks/html5_css3.pdf");
// I have used this url for this context only
org.apache.commons.io.FileUtils.copyURLToFile(url, file);
return null;
}
};
showPopup(downloadTask);
return downloadTask;
}
Popup showPopup(Task downloadTask)
{
ProgressIndicator progressIndicator = new ProgressIndicator();
progressIndicator.progressProperty().bind(downloadTask.progressProperty());
Popup progressPop = new Popup();
progressPop.getContent().add(progressIndicator);
progressPop.show(stage);
return progressPop;
// I have left out function to remove popup for simplicity
}
public static void main(String[] args)
{
launch(args);
}}
如果有例外,你不會知道它。註冊一個'onFailed'處理程序,任務:'downloadTask.setOnFailed(e - > downloadTask.getException()。printStackTrace());'。如果你想改變進度,你需要調用['updateProgress(...)'](http://docs.oracle.com/javase/8/javafx/api/javafx/concurrent/Task.html#updateProgress -long-long-)來自你的'call()'方法。 –