我正在尝试创建一个从文件中读取单词并在JavaFx标签上显示它们的方法。我这样做是通过使用服务和任务进行后台工作,同时使用Platform.runLater()与GUI进行通信。问题是该工作实际上已完成,但它只显示来自该文件的最后一个字。这是代码:
@FXML
private void launchLecture() {
if (stateFile)
mainApp.textTreatment();
System.out.println("Done");
if ((new File(mainApp.getLinkToPdf()).exists())) {
File fl = new File(mainApp.getLinkToPdf());
Service<Void> service = new Service<Void>() {
@Override
protected Task<Void> createTask() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
Scanner sc = new Scanner(fl);
final CountDownLatch latch = new CountDownLatch(1);
Platform.runLater(() -> {
try {
int count = 3;
while (count >= 0) {
wordToShow.setText(count + "...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count--;
}
// ---
while (sc.hasNext()) {
wordToShow.setText(sc.next().toString());
try {
Thread.sleep(speed);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally{
latch.countDown();
}
});
latch.await();
return null;
}
};
}
};
service.start();
}
}
我尝试了很多我在StackOverFlow上找到的解决方案,但仍然无法解决问题。