如何在放置在不同窗格/区域中的两个节点之间绘制线条

时间:2017-03-30 10:54:43

标签: javafx draw shape

我正试着画一个家谱树。在我的树中,我存储有关前合作伙伴的信息。所以小组(地区)的人看起来像这样

Z * * * Z * * * Z * * * X --- Y

Z代表exPartner,X代表Persion,Y代表现任妻子/丈夫

现在我想绘制一条线来连接与孩子们的当前关系。和孩子们的关系。 (图形上会有一行beetwen Z和*)

但是当人在其他区域时,LayoutX和LayoutX属性返回相对值。  我该怎么做,以及动态调整此面板的大小?我想Z应该总是在连接孩子的水平线的中间。

1 个答案:

答案 0 :(得分:3)

给定任何节点,您可以在同一场景图中的任何其他节点的坐标系中获取其边界:

Node nodeOfInterest = ... ;
Node anotherNode = ... ;

// ...

Bounds boundsInScene = nodeOfInterest.localToScene(nodeOfInterest.getBoundsInLocal());
Bounds boundRelativeToAnotherNode = anotherNode.sceneToLocal(boundsInScene);

因此,假设您有某种窗格,它是要连接的两个节点的共同祖先,您可以这样做:

Pane commonAncestor = ... ;
Node n1 = ... ;
Node n2 = ... ;

Bounds n1InCommonAncestor = getRelativeBounds(n1, commonAncestor);
Bounds n2InCommonAncestor = getRelativeBounds(n2, commonAncestor);
Point2D n1Center = getCenter(n1InCommonAncestor);
Point2D n2Center = getCenter(n2InCommonAncestor);

Line connector = new Line(n1Center.getX(), n1Center.getY(), n2Center.getX(), n2Center.getY());
commonAncestor.getChildren().add(connector);

// ...

private Bounds getRelativeBounds(Node node, Node relativeTo) {
    Bounds nodeBoundsInScene = node.localToScene(node.getBoundsInLocal());
    return relativeTo.sceneToLocal(nodeBoundsInScene);
}

private Point2D getCenter(Bounds b) {
    return new Point2D(b.getMinX() + b.getWidth() / 2, b.getMinY() + b.getHeight() / 2);
}
相关问题