弄清楚如何在javaFX中更新我的标签以匹配模拟时钟

时间:2016-07-10 23:49:46

标签: javafx

我正在试图弄清楚如何更新标签并显示当前时间,就像模拟时钟一样,提前感谢你。出于某种原因,这个网站不会让我发布,除非我做了一个充满文字的长期解释。无论是那个还是你必须比我更聪明才能使用该网站。我希望这很冗长。

public class Homework7 extends Application {

  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    // Create a clock and a label
    ClockPane clock = new ClockPane();
    String timeString = clock.getHour() + ":" + clock.getMinute() 
      + ":" + clock.getSecond();
    Label lblCurrentTime = new Label(timeString);


    // Place clock and label in border pane
    BorderPane pane = new BorderPane();
    pane.setCenter(clock);
    pane.setBottom(lblCurrentTime);
    BorderPane.setAlignment(lblCurrentTime, Pos.TOP_CENTER);

    // Create a scene and place it in the stage
    Scene scene = new Scene(pane, 250, 250);
    primaryStage.setTitle("Christian Beckman"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage

    // Create a handler for animation
    EventHandler<ActionEvent> eventHandler = e -> {
      clock.setCurrentTime(); // Set a new clock time
    };

    // Create an animation for a running clock
    Timeline animation = new Timeline(
    new KeyFrame(Duration.millis(1000), eventHandler));
    animation.setCycleCount(Timeline.INDEFINITE);
    animation.play(); // Start animation

    // Create a scene and place it in the stage
    // Scene scene = new Scene(clock, 250, 250);
    primaryStage.setTitle("Christian Beckman"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage
  }
}

1 个答案:

答案 0 :(得分:0)

更新时钟后只需更新Label文字:

...
EventHandler<ActionEvent> eventHandler = e -> {
    clock.setCurrentTime(); // Set a new clock time
    update(lblCurrentTime, clock);
};
...


private static void update(Label label, Clock clock) {
     String text = ...;
     label.setText(text);
}

如果ClockPane类返回格式正确的String s(例如"07"秒= 7),只需像Label文本的初始化一样计算文本:< / p>

 String text = clock.getHour() + ":" + clock.getMinute() + ":" + clock.getSecond();

如果这些方法返回int,您可以使用DateTimeFormatter

private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
String text = LocalTime.of(clock.getHour(), clock.getMinute(), clock.getSecond()).format(FORMATTER);