Trying to implement a coding solution for a programming project, below is what the output should be:
Specifically, the relavant goal in non-picture form is:
A private event handler that handles mouse clicks that adds a point with a left click,
removes a point with a right click and recomputes the maximal point set afterward
A private method that finds the maximal set and draws the lines that connect them
My implementation (or where I’ve narrowed down the errors):
public class PointPane extends Pane {
private final ArrayList<Point> points;
public PointPane(ArrayList<Point> points) {
this.points = points;
drawPoints();
this.setOnMouseClicked(this::handleMouseClick);
}
// this is the section with the first issue
private void handleMouseClick(MouseEvent event) {
// after entry it should be checking for the left or right mouse button, but
// it does not enter either the if or the else if and goes directly to
// drawPoints();
if (event.isPrimaryButtonDown()) { // Left click
points.add(new Point(event.getX(), event.getY()));
} else if (event.isSecondaryButtonDown()) { // Right click
Point pointToRemove = null;
for (Point point : points) {
if (Math.abs(point.getX() - event.getX())
< 5 && Math.abs(point.getY() - event.getY()) < 5) {
pointToRemove = point;
break;
}
}
if (pointToRemove != null) {
points.remove(pointToRemove);
}
}
drawPoints();
}
private void drawPoints() {
this.getChildren().clear();
for (Point point : points) {
javafx.scene.shape.Circle circle =
new javafx.scene.shape.Circle(
point.getX(), point.getY(), 5);
this.getChildren().add(circle);
}
findAndDrawMaximalSet();
}
… // This is the second issue
private void findAndDrawMaximalSet() {
ArrayList<Point> maximalSet = new ArrayList<>();
for (Point point : points) {
boolean isMaximal = true;
for (Point other : points) {
if (point != other && point.isBelowAndToLeftOf(other)) {
isMaximal = false;
break;
}
}
if (isMaximal) {
maximalSet.add(point);
}
}
if (maximalSet.size() >= 2) {
Collections.sort(maximalSet);
drawLines(maximalSet);
}
}
private void drawLines(ArrayList<Point> maximalSet) {
this.getChildren().removeIf(node -> node instanceof Line);
if (maximalSet.size() >= 2) {
for (int i = 0; i < maximalSet.size() - 1; i++) {
Point p1 = maximalSet.get(i);
Point p2 = maximalSet.get(i + 1);
Line line = new Line(p1.getX(), p1.getY(),
p2.getX(), p2.getY());
this.getChildren().add(line);
}
}
}
}