簡體   English   中英

如何監視文本java fx中的打印持續時間?

[英]How can I monitor the duration of printing in text java fx?

無論如何,我可以監視javafx中的持續時間嗎?

可以這樣說

System.out.println("Printing Duration: " + duration++);

這是我通常為任務計時的方式。 本示例跟蹤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);
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM