获取秒值并显示到控制台 window

Get seconds value and display to console window

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

如何获取当前秒数并将其显示给控制台window? 输出应该显示每一行的当前秒数,如: 5个 4个 3个 2个 1个 0

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 以响应倒计时更改值,则最好使用已经拥有的那种绑定,恕我直言。