反正我可以监视javafx中的持续时间吗?
让我们这样说吧
System.out.println("Printing Duration: " + duration++);
答案 0 :(得分:2)
这是我通常为任务计时的方式。本示例跟踪ProgressBar
完成所需的秒数。关键是在Timeline
开始时启动Task
,在Timeline
完成时结束Task
。
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.concurrent.Task;
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;
import javafx.util.Duration;
public class Example extends Application
{
@Override
public void start(Stage stage)
{
AtomicInteger atomicInteger = new AtomicInteger();
Label label = new Label("0 seconds");
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), (event) -> {
System.out.println(atomicInteger.incrementAndGet() + " seconds.");
label.setText(atomicInteger.get() + " seconds");
}));
timeline.setCycleCount(Timeline.INDEFINITE);
Task<Void> task = new Task<Void>()
{
@Override
protected Void call() throws Exception
{
Random random = new Random();
int randomNumber = random.nextInt(100) + 100;
for (int i = 0; i < randomNumber; i++) {
updateProgress(i, randomNumber);
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
};
task.setOnSucceeded((event) -> {
timeline.stop();
});
ProgressBar progressBar = new ProgressBar(0);
progressBar.progressProperty().bind(task.progressProperty());
Button button = new Button("Start");
button.setOnAction((event) -> {
button.setDisable(true);
timeline.play();
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
});
VBox root = new VBox(label, progressBar, button);
Scene scene = new Scene(root, 500, 500);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args)
{
launch(args);
}
}