gekrone
gekrone

Reputation: 179

Is there any way to bind a Node to the midpoint of a Line?

What I need to do is draw a Text in the middle of a Line. This is what I originally came up with:

Text tWeight = new Text(Integer.toString(e.getWeight()));
tWeight.setX((e.getEdge().getStartX() + e.getEdge().getEndX()) / 2);
tWeight.setY((e.getEdge().getStartY() + e.getEdge().getEndY()) / 2);

Where e.getEdge() returns a Line.
The problem is that the Line returned also has a bind between two Nodes, so when I try to get its position it returns the coordinates of the upper left corner of the Pane where the Line exists. Is there any way (or trick) to make this work from the start?

Thanks in advance

Upvotes: 2

Views: 189

Answers (1)

fabian
fabian

Reputation: 82461

DoubleExpression (supertype of DoubleProperty) provides the add(ObservableNumberValue) and multiply(double) methods. You can use those to create an expression for (startX+endX)*0.5 (or equivalent for y):

Line l = e.getEdge();
tWeight.xProperty().bind(l.startXProperty().add(l.endXProperty()).multiply(0.5));
tWeight.yProperty().bind(l.startYProperty().add(l.endYProperty()).multiply(0.5));

Upvotes: 2

Related Questions