How to draw line between two nodes placed in different Panes / Regions

一笑奈何 提交于 2019-12-06 13:55:30

Given any node, you can get its bounds in the coordinate system of any other node in the same scene graph with:

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

// ...

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

So assuming you have some kind of pane which is a common ancestor to two nodes you want to connect, you can do this:

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);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!