gpt4 book ai didi

java - 获取秒值并显示到控制台窗口

转载 作者:行者123 更新时间:2023-11-30 08:13:19 26 4
gpt4 key购买 nike

我在 JavaFX 中编写了一个简单的倒数计时器,并通过绑定(bind)实现了计时器,因此每当 timeSeconds 的值发生变化时,timerLabel 文本也会发生变化。

如何获取当前秒数并将其显示到控制台窗口?输出应在每个新行显示当前秒数的值,如下所示:543210

public class FXTimerBinding extends Application
{
// private class constant and somme variables
private static final Integer STARTTIME = 5;
private Timeline timeline;
private Label timerLabel = new Label();
private IntegerProperty timeSeconds = new SimpleIntegerProperty(STARTTIME);

@Override
public void start(Stage primaryStage)
{
// setup the Stage and the Scene(the scene graph)
primaryStage.setTitle("FX Timer binding");
Group root = new Group();
Scene scene = new Scene(root, 300, 250);

// configure the label
timerLabel.setText(timeSeconds.toString());
timerLabel.setTextFill(Color.RED);
timerLabel.setStyle("-fx-font-size: 4em;");

// Bind the timerLabel text property to the timeSeconds property
timerLabel.textProperty().bind(timeSeconds.asString());

// create and configure the Button
Button button = new Button("Start timer");
button.setOnAction(new EventHandler<ActionEvent>(){

@Override
public void handle(ActionEvent event)
{
if(timeline != null)
timeline.stop();

timeSeconds.set(STARTTIME);
timeline = new Timeline();

KeyValue keyValue = new KeyValue(timeSeconds, 0);
KeyFrame keyFrame = new KeyFrame(Duration.seconds(STARTTIME + 1), keyValue);

timeline.getKeyFrames().add(keyFrame);
timeline.playFromStart();

System.out.println("get every seconds value and display to console window");
}
});

来自:http://www.asgteach.com/blog/?p=334

最佳答案

如果您想在 timeSeconds 的实际值发生变化时执行其他操作,只需为其添加一个监听器即可:

timeSeconds.addListener((observable, oldTimeValue, newTimeValue) -> {
// code to execute here...
// e.g.
System.out.println("Time left: "+newTimeValue);
});

但是,如果您要更改 UI 以响应倒计时更改值,那么最好使用已有的绑定(bind),恕我直言。

关于java - 获取秒值并显示到控制台窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30036525/

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