package FXExample;
import javafx.animation.PathTransition;
import javafx.animation.PathTransitionBuilder;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Point2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.SceneBuilder;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.RadialGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Circle;
import javafx.scene.shape.CircleBuilder;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.stage.Stage;
import javafx.util.Duration;
public class WorkingWithTheSceneGraph extends Application{
Path onePath = new Path();
Point2D anchorPt;//anchor:锚
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Chapter 2-3 Working with the Scene Graph");
final Group root = new Group();
root.getChildren().add(onePath);
final Scene scene = SceneBuilder.create()
.root(root)
.width(300)
.height(300)
.fill(Color.PINK)
.build();
RadialGradient gradient1 = new RadialGradient(0,.1,100,100,20,false,CycleMethod.NO_CYCLE,
new Stop(0,Color.RED),new Stop(1,Color.BLACK));
//sphere:n. 范围;球体
final Circle sphere = CircleBuilder.create()
.centerX(100).centerY(100).radius(20).fill(gradient1).build();
root.getChildren().add(sphere);
// animate sphere by following the path.通过下面的路径动画
final PathTransition pathTransition = PathTransitionBuilder.create()
.duration(Duration.millis(4000))//持续时间
.cycleCount(1)//循环周期
.node(sphere)//形状
.path(onePath)//路径
.orientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT)//方向
.build();
// once finished clear path.结束后清除路径
pathTransition.onFinishedProperty().set(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
onePath.getElements().clear();
}});
// starting initial path:初始路径
scene.onMousePressedProperty().set(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
onePath.getElements().clear();
anchorPt = new Point2D(event.getX(),event.getY());
onePath.setStroke(Color.BLACK);
onePath.setStrokeWidth(3);
onePath.getElements().add(new MoveTo(anchorPt.getX(),anchorPt.getY()));
}});
// dragging creates lineTos added to the path拖动创建lineTos添加到路径
scene.onMouseDraggedProperty().set(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
onePath.getElements().add(new LineTo(event.getX(),event.getY()));
}});
scene.onMouseReleasedProperty().set(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
onePath.setStrokeWidth(10);
if(onePath.getElements().size() > 1){
pathTransition.stop();
pathTransition.playFromStart();
}
}});
primaryStage.setScene(scene);
primaryStage.show();
}
}