java - setTitle() 和 Thread.sleep()

标签 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();
            }



    }

}
}

感谢您的帮助! ;)

最佳答案

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

首先,请通读 Concurrency in JavaFX

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

你可以...

使用时间轴

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);
    }

}

关于java - setTitle() 和 Thread.sleep(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49583385/

相关文章:

java - Android int 在 eclipse 中替换为 android.R.integer

java - 第一次打开eclipse失败

java - java从xml文档接收子节点

java - Java Petstore 2.0 蓝图

Java-为ImageDescriptor设置相对地址

java - 什么是 JVM 可以创建的线程的阈值限制数

python - 唤醒休眠线程的最佳方式?

java - 从另一个类调用扩展 Thread 的类的方法

java - 在 JPanel 中获得良好的网格布局

java - Hibernate:在扩展另一个注释为 JoinedSubclass 的类的类上使用 mappedBy?