Как линией соединить два круга
Мне надо соединить два круга линией, и у меня есть две проблемы.
Вот что я смог придумать:
EventHandler<MouseEvent> lineDrawEvent =
new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent t) {
if (penLine.isDisable()) {
if (x1 == 0 && y1 == 0) {
x1 = t.getSceneX();
y1 = t.getSceneY();
} else {
if (x2 == 0 && y2 == 0) {
x2 = t.getSceneX();
y2 = t.getSceneY();
Line line = new Line(x1, y1, x2, y2);
MyApplication.pane.getChildren().add(line);
x1 = 0;
x2 = 0;
y1 = 0;
y2 = 0;
}
}
}
}
};
Как сделать так, чтобы линия рисовалась именно когда пользователь жмет на круг (у меня для рисования линии не обязательно наличие кругов).
Как сделать так, чтобы после нажатия на один круг, линия как бы тянулась за курсором, пока мы не нажмем на второй круг.
Ответы (1 шт):
Автор решения: Asad Ganiev
→ Ссылка
Как-то я реализовал такую штуку, но к сожалению не нашел тот пример кода.
По памяти я написал пример кода, думаю вы поймете суть идеи.
import javafx.application.Application;
import javafx.geometry.Bounds;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class DrawLineApp extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Scene scene = new Scene(new Board());
primaryStage.setScene(scene);
primaryStage.setMaximized(true);
primaryStage.show();
}
public class Board extends AnchorPane {
private Line line;
private final Circle circle1;
private final Circle circle2;
public Board() {
circle1 = new Circle(10, Color.RED);
circle2 = new Circle(10, Color.RED);
circle1.setOnMousePressed(e -> {
Bounds bounds = circle1.localToParent(circle1.getBoundsInLocal());
double x = (bounds.getMaxX() + bounds.getMinX()) / 2;
double y = (bounds.getMaxY() + bounds.getMinY()) / 2;
if (line == null) {
line = new Line(x, y, x, y);
line.setStrokeWidth(1.);
line.setFill(Color.BLUE);
} else {
getChildren().remove(line);
line.setStartX(x);
line.setStartY(y);
line.setEndX(x);
line.setEndY(y);
}
getChildren().add(line);
});
circle1.setOnMouseDragged(e -> {
line.setEndX(e.getSceneX());
line.setEndY(e.getSceneY());
});
circle1.setOnMouseReleased(e -> {
if (circle2.getBoundsInParent().contains(e.getSceneX(), e.getSceneY())) {
Bounds bounds = circle2.localToParent(circle2.getBoundsInLocal());
double x = (bounds.getMaxX() + bounds.getMinX()) / 2;
double y = (bounds.getMaxY() + bounds.getMinY()) / 2;
line.setEndX(x);
line.setEndY(y);
} else {
getChildren().remove(line);
}
});
AnchorPane.setTopAnchor(circle1, 150.);
AnchorPane.setLeftAnchor(circle1, 150.);
AnchorPane.setTopAnchor(circle2, 150.);
AnchorPane.setLeftAnchor(circle2, 350.);
getChildren().addAll(circle1, circle2);
}
}
}