JavaFX: Beispiel Animation
Beispiel für Animation in JavaFX
Anim.java
—
Java source code,
2 KB (2719 bytes)
Dateiinhalt
package anim; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.PathTransition; import javafx.animation.PathTransition.OrientationType; import javafx.animation.Timeline; import javafx.application.Application; import javafx.geometry.Point2D; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.CubicCurveTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class Anim extends Application { Point2D lastMousePos; public void start(Stage primaryStage) { Rectangle rectangle = new Rectangle(10, 10, 30, 30); Circle circle = new Circle(100, 100, 30); circle.setScaleX(1.5); circle.setFill(Color.CORAL); Pane pane = new Pane(circle, rectangle); primaryStage.setScene(new Scene(pane, 500, 500)); primaryStage.show(); // Timeline KeyFrame f1 = new KeyFrame(Duration.seconds(1), new KeyValue(rectangle.translateXProperty(), 100), new KeyValue(rectangle.translateYProperty(), 0)); KeyFrame f2 = new KeyFrame(Duration.seconds(2), new KeyValue(rectangle.translateXProperty(), 100), new KeyValue(rectangle.translateYProperty(), 100)); Timeline tl = new Timeline(); tl.getKeyFrames().addAll(f1, f2); tl.setCycleCount(2); // 2 wiederholen (1 normal + 1 reversed) tl.setAutoReverse(true); tl.play(); pane.addEventHandler(MouseEvent.MOUSE_PRESSED, e -> { lastMousePos = new Point2D(e.getSceneX(), e.getSceneY()); tl.play(); }); pane.addEventHandler(MouseEvent.MOUSE_DRAGGED, e -> { pane.setTranslateX(pane.getTranslateX() + (e.getSceneX() - lastMousePos.getX())); pane.setTranslateY(pane.getTranslateY() + (e.getSceneY() - lastMousePos.getY())); lastMousePos = new Point2D(e.getSceneX(), e.getSceneY()); }); // Transition: vorgefertigte Animationen Path path = new Path(); path.getElements().add(new MoveTo(100, 150)); path.getElements().add(new CubicCurveTo(100, 200, 250, 200, 200, 110)); PathTransition pathTransition = new PathTransition(); pathTransition.setDuration(Duration.millis(1000)); pathTransition.setNode(circle); pathTransition.setPath(path); pathTransition.setOrientation(OrientationType.ORTHOGONAL_TO_TANGENT); pathTransition.setCycleCount(PathTransition.INDEFINITE); pathTransition.setAutoReverse(true); pathTransition.play(); } public static void main(String[] args) { launch(args); } }
Artikelaktionen