使用折线JavaFX连接圆圈

时间:2016-03-03 02:59:38

标签: javafx polyline

我在JavaFX的图表上创建了圆圈,我想用折线连接这些圆圈。有谁知道这样做的语法?谢谢!

2 个答案:

答案 0 :(得分:1)

Polyline可能有效,但如果您使用the Path class,则可以更轻松地执行此操作,因为这样您就可以访问the individual elements of the path (PathElements)。您可以使用绑定将线点的位置绑定到圆的位置。这样,即使您稍后移动圆圈,线条也会保持在适当的位置。

实施例

private static void bindLinePosTo(Circle circle, LineTo lineTo) {
    lineTo.xProperty().bind(circle.centerXProperty());
    lineTo.yProperty().bind(circle.centerYProperty());
}

private static void animate(Circle circle, Duration duration, double dy) {
    Timeline animation = new Timeline(
            new KeyFrame(Duration.ZERO, new KeyValue(circle.centerYProperty(), circle.getCenterY())),
            new KeyFrame(duration, new KeyValue(circle.centerYProperty(), circle.getCenterY()+dy)));
    animation.setAutoReverse(true);
    animation.setCycleCount(Animation.INDEFINITE);
    animation.play();
}

@Override
public void start(Stage primaryStage) {
    MoveTo start = new MoveTo();
    LineTo line1 = new LineTo();
    LineTo line2 = new LineTo();

    Circle c1 = new Circle(10, 100, 5);
    Circle c2 = new Circle(50, 100, 5);
    Circle c3 = new Circle(100, 100, 5);

    c1.setFill(Color.RED);
    c2.setFill(Color.RED);
    c3.setFill(Color.RED);

    start.xProperty().bind(c1.centerXProperty());
    start.yProperty().bind(c1.centerYProperty());
    bindLinePosTo(c2, line1);
    bindLinePosTo(c3, line2);

    Path path = new Path(start, line1, line2);

    Pane root = new Pane(path, c1, c2, c3);

    animate(c1, Duration.seconds(1), 100);
    animate(c2, Duration.seconds(2), 50);
    animate(c3, Duration.seconds(0.5), 150);

    Scene scene = new Scene(root, 110, 300);
    primaryStage.setScene(scene);
    primaryStage.show();
}

答案 1 :(得分:0)

使用Binding API,e。 G。 like this