我写了一段代码,用于从互联网下载文件(在后台服务中),并在弹出的阶段显示下载进度。代码编译成功,没有运行时错误。然而,没有下载发生,并且进度指示器保持不确定。进度指示器保持不确定状态,没有下载
该代码是为了说明我的观点而定制的。请看看它,让我明白我出错的地方。
谢谢!
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()'方法。 –