Wednesday, May 21, 2014

JavaFX 8 TranslateTransition

Example of JavaFX animation of TranslateTransition:


package javafx8_animation;

import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 *
 * @web java-buddy.blogspot.com
 */
public class JavaFX8_Animation extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Group root = new Group();
        Scene scene = new Scene(root, 500, 350, Color.BLACK);
        scene.setFill(Color.WHITE);
        
        Rectangle rect1 = new Rectangle(60, 30, 350, 200);
        rect1.setFill(Color.BLUEVIOLET);
        rect1.setStroke(Color.RED);
        rect1.setStrokeWidth(10);
        
        TranslateTransition translateTransition1 = new TranslateTransition(Duration.millis(500), rect1);
        translateTransition1.setByX(40);
        translateTransition1.setByY(70);
        translateTransition1.setCycleCount(2);
        translateTransition1.setAutoReverse(true);
        rect1.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent event) -> {
            translateTransition1.play();
        });

        //Rectangle with LinearGradient Transparence background
        Stop[] stopsTransparence = new Stop[] { 
            new Stop(0, Color.color(0.0, 1.0, 1.0 ,1.0)), 
            new Stop(1, Color.color(0.0, 1.0, 1.0 ,0.0))};
        LinearGradient linearGradientTransparence = 
                new LinearGradient(0, 0, 1, 0, true, 
                        CycleMethod.NO_CYCLE, stopsTransparence);
        
        Rectangle rect2 = new Rectangle(100, 100, 250, 200);
        rect2.setFill(linearGradientTransparence);
        rect2.setStroke(Color.BLUE);
        rect2.setStrokeWidth(10);
        
        TranslateTransition translateTransition2 = new TranslateTransition(Duration.millis(500), rect2);
        translateTransition2.setByX(-40);
        translateTransition2.setByY(-70);
        translateTransition2.setCycleCount(2);
        translateTransition2.setAutoReverse(true);
        rect2.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent event) -> {
            translateTransition2.play();
        });
        
        root.getChildren().addAll(rect1, rect2);

        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}

No comments:

Post a Comment