Understanding KeyFrame and KeyValue

KeyFrame works tightly with the Duration class, which is responsible for measuring time intervals. The Duration API is straightforward—you choose a time unit, how many of them you need, and how to combine them. See the following examples:

Duration.seconds(5);
Duration.hours(1).add(Duration.minutes(15));
Duration.valueOf("10ms");
new Duration(100); // default unit is milliseconds
Duration.ZERO;

For a specified Duration, you can select one or several KeyValue objects. KeyValue takes two parameters—the property you want to set and a value of the corresponding type.

Note that you don't have to set initial values in the first KeyFrame with Duration.ZERO—if they are missing, Timeframe will use the current values of these properties. For example, for the sample from the previous section, this autogenerated KeyFrame may look as follows:

new KeyFrame(Duration.ZERO, new KeyValue(circle.translateXProperty(), circle.getTranslateX());

Also, you don't have to use the same properties for each KeyFrame, but Timeline will calculate each used property for each KeyFrame. For example, look at the following code:

// chapter5/basics/CombinedAnimation.java
KeyFrame keyFrame = new KeyFrame(Duration.seconds(5),
new KeyValue(circle.translateXProperty(), 200));

KeyFrame keyFrame2 = new KeyFrame(Duration.seconds(10),
new KeyValue(circle.translateYProperty(), 200));

Timeline timeline = new Timeline(keyFrame, keyFrame2);

The first impression is that the circle will move horizontally for the first 5 seconds, then vertically for another 5. But instead, Timeline will move the circle horizontally for 5 seconds and simultaneously move it vertically for 10 seconds. The final trajectory of the circle will be as follows (shown in gray):

Here, you can see that the horizontal coordinate changed for 5 seconds only, but the vertical coordinate changed from 0 to 10 seconds.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.156.251