问题
For assignment, I created 2 draggable circle and connect them with line with javaFX.
I need add text which calculate distance between two circle (or length of line) and that text need to keep updating when I drag circles, but that's where I stuck
Circle circle1 = new Circle();
circle1.setCenterX(40);
circle1.setCenterY(40);
circle1.setRadius(10);
Circle circle2 = new Circle();
circle2.setCenterX(120);
circle2.setCenterY(150);
circle2.setRadius(10);
Line line = new Line ();
line.startXProperty().bind(circle1.centerXProperty());
line.startYProperty().bind(circle1.centerYProperty());
line.endXProperty().bind(circle2.centerXProperty());
line.endYProperty().bind(circle2.centerYProperty());
circle1.setOnMousePressed(mousePressEventHandler);
circle1.setOnMouseDragged(mouseDragEventHandler);
circle2.setOnMousePressed(mousePressEventHandler);
circle2.setOnMouseDragged(mouseDragEventHandler);
it's my two circles and line, and I tried
Text distance = new Text();
distance.textProperty().bind(circle1.centerXProperty()-circle2.centerXProperty() . . .);
However, as you know as, I can't normally calculate Property value, and I have no idea how should I do it.
回答1:
You could create a DoubleProperty
DoubleProperty distanceProperty = new SimpleDoubleProperty();
and a ChangeListener in which you calculate the distance
ChangeListener<Number> changeListener = (observable, oldValue, newValue) -> {
Point2D p1 = new Point2D(circle1.getCenterX(), circle1.getCenterY());
Point2D p2 = new Point2D(circle2.getCenterX(), circle2.getCenterY());
distanceProperty.set(p1.distance(p2));
};
assign the listener
circle1.centerXProperty().addListener( changeListener);
circle1.centerYProperty().addListener( changeListener);
circle2.centerXProperty().addListener( changeListener);
circle2.centerYProperty().addListener( changeListener);
and bind the distanceProperty to the text
Text text = new Text();
text.textProperty().bind(distanceProperty.asString());
来源:https://stackoverflow.com/questions/36025841/javafx-distance-between-two-circle-and-keep-updating-property