gpt4 book ai didi

java - 跑表。数秒。 javafx

转载 作者:行者123 更新时间:2023-12-01 09:37:42 26 4
gpt4 key购买 nike

我想制作一个秒表(小时:分钟:秒),我想我应该按以下方式进行。变量结果将传递到我的 TextField 中,startTime 将是我们启动秒表的时间,传递的时间将是当前时间(常量)

result=startTime-elapsedTime;

但我不知道要使用哪个日期类,也不知道如何重复此操作。

result=startTime-elapsedTime; 每秒更新 TextField。

欢迎所有建议。

最佳答案

您可以使用 TimeLine 动画来更新 TextField:

 public void startTimer() {
timeline = new Timeline(
new KeyFrame(Duration.seconds(0),
e ->advanceDuration()),
new KeyFrame(Duration.seconds(1)));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}

private void advanceDuration() {
if (seconds < 59) {
seconds++;
} else {
seconds = 0;
if (minutes < 59) {
minutes++;
}else{
minutes = 0;
hours++;
}
}
updateDisplay();
}

编辑:

根据评论,这里是使用 AnimationTimer 的解决方案:

public class Timer extends Application {

private AnimationTimer timer;
private Label lblTime = new Label("0 .s");
private int seconds;

@Override
public void start(Stage primaryStage) {
timer = new AnimationTimer() {

private long lastTime = 0;

@Override
public void handle(long now) {
if (lastTime != 0) {
if (now > lastTime + 1_000_000_000) {
seconds++;
lblTime.setText(Integer.toString(seconds) + " .s");
lastTime = now;
}
} else {
lastTime = now;

}
}

@Override
public void stop() {
super.stop();
lastTime = 0;
seconds = 0;
}
};

Button btnStart = new Button("START");
btnStart.setOnAction(e ->
{
lblTime.setText("0 .s");
timer.start();
});

Button btnStop = new Button("STOP");
btnStop.setOnAction(e -> timer.stop());


VBox box = new VBox(16, lblTime, btnStart, btnPause);
box.setAlignment(Pos.CENTER);

primaryStage.setScene(new Scene(new StackPane(box)));
primaryStage.show();
}

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

关于java - 跑表。数秒。 javafx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38717690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com