我最近开始使用JavaFx 2.0
,也许我的问题非常基本,但目前我不知道如何解决它。例如,假设我有一个名为Clock的小型演示应用程序:
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
将每隔5秒更新一次Label
。但我面临的问题是,当我点击开始按钮时,我必须等待5秒,直到Timeline
开始运行,并在Label
更新时间。那么,有没有办法消除这个初始延迟时间?提前谢谢。
答案 0 :(得分:8)
我遇到了同样的问题,我在KeyFrame
的开头添加Duration.ZERO
timeline
并将其添加到第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)));
答案 1 :(得分:0)
您可以在相关关键帧之前跳转到(1 ms,如果准确度不是那么重要)时转发时间轴:
timeline.playFrom(Duration.millis(4999));