我在JavaFX中编写了一个简单的倒计时器,并使用绑定实现Timer,因此每当timeSeconds的值发生变化时,timerLabel文本也会发生变化。
如何获取当前秒的值并将其显示到控制台窗口? 输出应显示每个新行的当前秒的值,如: 五 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");
}
});
答案 0 :(得分:1)
如果要在timeSeconds
的实际值发生变化时执行其他操作,只需向其添加一个侦听器:
timeSeconds.addListener((observable, oldTimeValue, newTimeValue) -> {
// code to execute here...
// e.g.
System.out.println("Time left: "+newTimeValue);
});
如果您正在更改UI以响应倒计时更改值,那么已经拥有的那种绑定更可取,imho。