我试图在 for 循环中更新 ProgressBar
值。它的进度应该每 100 毫秒更新一次,但不幸的是它没有用!这是代码:
pb = new ProgressBar(0);
Button btn = new Button("Start!");
btn.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
for(int i = 0; i <=100; i++){
position = i;
Platform.runLater(new Runnable(){
@Override
public void run() {
pb.setProgress(position);
System.out.println("Index: "+position);
}
});
try{
Thread.sleep(100);
}catch(Exception e){ System.err.println(e); }
}
}
});
问题 1: 我希望上面的代码每 100 毫秒更新一次进度条,但它没有工作。为什么?
问题 2: 我在循环中调用了 System.out.println("Index: "+position);
。我假设输出应该是 1..2..3..4...
但我错了。输出是这样的:
Index: 100
Index: 100
Index: 100
Index: 100
Index: 100
Index: 100
Index: 100
最佳答案
通过手动计算和设置柱的 progressProperty 来重新发明轮子的替代方法是使用任务:它有一个 progressProperty 自动计算相对数量并保证在 FX 应用程序线程上更新,例如可以安全地将任何与场景相关的属性绑定(bind)到。
类似于:
Task<Void> task = new Task<Void>() {
@Override
protected Void call() throws Exception {
double max = 137;
for (int i = 0; i <= max; i++) {
updateProgress(i, max);
Thread.sleep(100);
}
return null;
}
};
button.setOnAction(e -> {
// a task is not reusable, disable
button.setDisable(true);
// bind "late" to not get an initial indeterminate PB
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();
});
显然,这是最简单的片段 - 请参阅 Task有关取消/中断线程的示例。
关于java - 在 for 循环中更新 ProgressBar 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32757069/