Saturday, June 18, 2016

42. Animation

A rectangle is animated across the 4 sides of our window. It's speed is 2 times faster on the left side, as compared to the 3 other sides.


We use KeyValues and KeyFrames, and finally a Timeline. We could have used 4 TranslateTransitions. However using KeyValues and KeyFrames, we can interpolate any node Property.


package ex42;
 
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
 
public class Ex42 extends Application {
 
    @Override
    public void start(Stage primaryStage) {
 
        Rectangle rect = new Rectangle(50, 50, 20, 20);
        rect.setFill(Color.RED);
        KeyValue x50 = new KeyValue(rect.xProperty(), 50);
        KeyValue x350 = new KeyValue(rect.xProperty(), 350);
        KeyValue y50 = new KeyValue(rect.yProperty(), 50);
        KeyValue y350 = new KeyValue(rect.yProperty(), 350);
        
        KeyFrame kf1 = new KeyFrame(Duration.seconds(1),
                x350, y50);
        KeyFrame kf2 = new KeyFrame(Duration.seconds(2),
                x350, y350);
        KeyFrame kf3 = new KeyFrame(Duration.seconds(3),
                x50, y350);
        KeyFrame kf4 = new KeyFrame(Duration.seconds(5),
                x50, y50);
        
        Timeline timeline = new Timeline();
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.setAutoReverse(true);
        timeline.getKeyFrames().addAll(kf1, kf2, kf3, kf4);
        timeline.play();

        Group root = new Group(rect);
        Scene scene = new Scene(root, 400, 400);
        
        primaryStage.setTitle("Example 42. Animation");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

This is the output as the rectangle moves across left side:


No comments:

Post a Comment