setTitle()与Thread.sleep()

时间:2018-03-31 01:39:49

标签: java eclipse multithreading user-interface javafx

我刚刚在javafx中学到了一些新闻,然后我想申请它们,所以我选择制作一个柜台;但是当我在我的标签上设置了不会改变它的文本时;我用System.out.print测试了它,效果很好。 那是我的代码:

public class Controller {
@FXML
private Label time;
@FXML
private Button start;
public void Counter(ActionEvent event)
{
    start.setText("hello");
    time.setText("00 : 00 : 00");
    int h=0,m=0,s=0,i=0;
    while(true)
    {
        try {
            s++;
            if(s==60) {s=0;m++;}
            if(m==60) {m=0;h++;}
            System.out.println(Integer.toString(h)+" : "+String.valueOf(m)+" : "+String.valueOf(s));
            time.setText(Integer.toString(h)+" : "+String.valueOf(m)+" : "+String.valueOf(s));

                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



    }

}
}

感谢您的帮助! ;)

2 个答案:

答案 0 :(得分:1)

重要的是,您需要了解对UI的任何更新都需要在UI的主线程中完成。您还应该避免阻止UI的主线程,这将阻止UI更新。

首先,请阅读Concurrency in JavaFX

当您处理时间或持续时间时,应始终使用专用库,例如​​java.time。为什么?因为一天中实际上没有24小时或一分钟内没有60秒 - 我知道,不是很奇怪。

你可以......

使用Timeline

import java.time.LocalDateTime;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Test extends Application {

    private LocalDateTime startTime;
    private Timeline timer;

    private Label time;

    @Override
    public void start(Stage primaryStage) {
        time = new Label("...");
        Button btn = new Button();
        btn.setText("Start");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                if (timer != null) {
                    timer.stop();
                }
                startTime = LocalDateTime.now();
                timer = new Timeline(new KeyFrame(Duration.millis(500), new EventHandler<ActionEvent>() {

                    @Override
                    public void handle(ActionEvent event) {
                        LocalDateTime now = LocalDateTime.now();
                        java.time.Duration duration = java.time.Duration.between(startTime, now);
                        time.setText(format(duration));
                    }
                }));
                timer.setCycleCount(Timeline.INDEFINITE);
                timer.play();
            }
        });

        VBox root = new VBox();
        root.setAlignment(Pos.CENTER);
        root.getChildren().add(time);
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    protected String format(java.time.Duration duration) {
        long hours = duration.toHours();
        long mins = duration.minusHours(hours).toMinutes();
        long seconds = duration.minusMinutes(mins).toMillis() / 1000;
        return String.format("%02dh %02dm %02ds", hours, mins, seconds);
    }

    public static void main(String[] args) {
        launch(args);
    }

}

使用AnimationTimer

这可能是首选解决方案,因为计时器与动画引擎的帧刷新同步调用

import java.time.LocalDateTime;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Test extends Application {

    private LocalDateTime startTime;
    private AnimationTimer timer;

    private Label time;

    @Override
    public void start(Stage primaryStage) {
        time = new Label("...");
        Button btn = new Button();
        btn.setText("Start");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                if (timer != null) {
                    timer.stop();
                }
                startTime = LocalDateTime.now();
                timer = new AnimationTimer() {
                    @Override
                    public void handle(long click) {
                        LocalDateTime now = LocalDateTime.now();
                        java.time.Duration duration = java.time.Duration.between(startTime, now);
                        time.setText(format(duration));
                    }
                };
                timer.start();
            }
        });

        VBox root = new VBox();
        root.setAlignment(Pos.CENTER);
        root.getChildren().add(time);
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    protected String format(java.time.Duration duration) {
        long hours = duration.toHours();
        long mins = duration.minusHours(hours).toMinutes();
        long seconds = duration.minusMinutes(mins).toMillis() / 1000;
        return String.format("%02dh %02dm %02ds", hours, mins, seconds);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

答案 1 :(得分:0)

不应该使用while(true)循环来更新JavaFX GUI,而是可以使用AnimationTimer而不是

你可以试试这个

public void Counter(ActionEvent event)
{
        start.setText("hello");
        time.setText("00 : 00 : 00");

        AnimationTimer timer = new AnimationTimer() {
            long then=0;
            double sum=0;
            int h=0,m=0,s=0;

            @Override
            public void handle(long now) {
                long dt = now - then;
                sum+=dt;
                if(sum/1000000000>=1) {
                     s++;
                        if(s==60) {s=0;m++;}
                        if(m==60) {m=0;h++;}
                        System.out.println(Integer.toString(h)+" : "+String.valueOf(m)+" : "+String.valueOf(s));
                        time.setText(Integer.toString(h)+" : "+String.valueOf(m)+" : "+String.valueOf(s));
                    sum=0;
                }

                then=now;
            }

        };
        timer.start();
}