2013-08-18 151 views
4

我最近开始使用JavaFx 2.0,也许我的问题是非常基本的,但目前我不知道如何解决它。例如,让我们说我有这个小演示应用程序称为时钟:JavaFx时间轴 - 设置初始延迟

import javafx.animation.KeyFrame; 
import javafx.animation.Timeline; 
import javafx.application.Application; 
import javafx.event.ActionEvent; 
import javafx.event.EventHandler; 
import javafx.geometry.Insets; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.Label; 
import javafx.scene.layout.HBox; 
import javafx.scene.layout.HBoxBuilder; 
import javafx.scene.text.Font; 
import javafx.stage.Stage; 
import javafx.stage.WindowEvent; 
import javafx.util.Duration; 

import java.util.Date; 

public class ClockDemo extends Application { 

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

    @Override 
    public void start(Stage stage) throws Exception { 
     final Label label = new Label(new Date().toString()); 
     label.setFont(new Font("Arial", 18)); 
     final Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(5), new EventHandler<ActionEvent>() { 
      @Override 
      public void handle(ActionEvent actionEvent) { 
       label.setText(new Date().toString()); 
      } 
     })); 
     timeline.setCycleCount(Timeline.INDEFINITE); 

     Button button = new Button("Start"); 
     button.setOnAction(new EventHandler<ActionEvent>() { 
      @Override 
      public void handle(ActionEvent actionEvent) { 
       timeline.play(); 
      } 
     }); 

     stage.setOnCloseRequest(new EventHandler<WindowEvent>() { 
      @Override 
      public void handle(WindowEvent windowEvent) { 
       timeline.stop(); 
      } 
     }); 
     HBox hBox = HBoxBuilder.create() 
       .spacing(5.0) 
       .padding(new Insets(5, 5, 5, 5)) 
       .children(label, button) 
       .build(); 

     Scene scene = new Scene(hBox, 330, 30); 
     stage.setScene(scene); 
     stage.setTitle("Clock demo"); 
     stage.show(); 
    } 
} 

基本上,如果你点击开始按钮,Timeline将在Label每5秒更新一次。但我面临的问题是,当我点击开始按钮时,我必须等待5秒钟,直到Timeline开始运行并更新时间Label。那么,有什么办法可以消除这个初始延迟时间吗?提前致谢。

回答

8

我有同样的问题,我通过在timeline年初增加与Duration.ZERO一个KeyFrame解决它,我的行为给它添加和第二KeyFrame负责延迟。

final Timeline timeline = new Timeline(new KeyFrame(Duration.ZERO, new EventHandler<ActionEvent>() { 
       @Override 
       public void handle(ActionEvent actionEvent) { 
        label.setText(new Date().toString()); 
       } 
      }) , new KeyFrame(Duration.seconds(5))); 
+0

是的,这解决了这个问题。万分感谢。 –

0

您可以通过跳转到只与关键帧的转发之前的时间表(1毫秒,如果精度不那么重要):

timeline.playFrom(Duration.millis(4999));