我在javafx代码中有一个进度条,它显示了java应用程序中任务的剩余时间。我对该栏的代码如下:
task = taskCreator(saveSpeedInt);
pbar.progressProperty().unbind();
pbar.progressProperty().bind(task.progressProperty());
new Thread(task).start();
taskCreator:
Task<?> taskCreator(int seconds) {
return new Task<Object>() {
@Override
protected Object call() throws Exception {
for (int i = 0; i < seconds; i++) {
Thread.sleep(1000);
updateProgress(i + 1, seconds);
}
return true;
}
};
}
我想在我的界面中创建一个与进度条相同的标签,但是要说明时间(以相反的方式)。我怎么能这样做?任务的时间存储在saveSpeedInt中。
编辑:我最终想要的是在按钮事件发生时初始化计数器(从头开始计数),如何在您的示例中使用按钮实现这一目标?< / p>
答案 0 :(得分:2)
label.textProperty().bind(Bindings.createStringBinding(() ->
String.format("Seconds remaining: %.0f", saveSpeedInt * (1 - task.getProgress())),
task.progressProperty()));
或
label.textProperty().bind(
task.progressProperty()
.multiply(-1)
.add(1)
.multiply(saveSpeedInt)
.asString("Seconds remaining: %.0f"));
SSCCE:
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Counter extends Application {
private final int saveSpeedInt = 60 ;
@Override
public void start(Stage primaryStage) {
ProgressBar pbar = new ProgressBar();
Label label = new Label();
Button start = new Button("Start");
start.setOnAction(e -> {
Task<?> task = taskCreator(saveSpeedInt);
pbar.progressProperty().bind(task.progressProperty());
new Thread(task).start();
label.textProperty().bind(
task.progressProperty()
.multiply(-1)
.add(1)
.multiply(saveSpeedInt)
.asString("Seconds remaining: %.0f"));
// label.textProperty().bind(Bindings.createStringBinding(() ->
// String.format("Seconds remaining: %.0f", saveSpeedInt * (1 - task.getProgress())),
// task.progressProperty()));
});
VBox root = new VBox(10, start, label, pbar);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 350, 120);
primaryStage.setScene(scene);
primaryStage.show();
}
private Task<Void> taskCreator(int seconds) {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
updateProgress(0, seconds);
for (int i = 0; i < seconds; i++) {
Thread.sleep(1000);
updateProgress(i + 1, seconds);
}
return null;
}
};
}
public static void main(String[] args) {
launch(args);
}
}