The assignment is to to a closest pair of points using brute force.
I seem to have most everything I need - the frame appears, circles appear where I click, and the closest pairs seem to highlight properly, I say "seems" because this is where my question lies. I need only two circles highlighted at any given time (the closest pair), but previous closest pairs do not de-select/unhighlight.
I hope this is something simple I have overlooked. I have been at this for a while, so it's very possible my mind and eyes are just too tired to pick this problem up. Hopefully, a fresh set of eyes will do me some good.
Any help is greatly appreciated.
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class AssignmentFour extends JFrame {
private final PointPanel canvas = new PointPanel();
public AssignmentFour() {
JPanel panel = new JPanel();
this.add(canvas, BorderLayout.CENTER);
this.add(panel, BorderLayout.SOUTH);
add(new JLabel("<html> Click anywhere within the panel."
+ "<BR> The two closest points will be highlighted.<BR>"
+ "Click the 'x' to exit program. </html>"), BorderLayout.SOUTH);
}//AssignmentFour method
public static void main(String[] args) {
AssignmentFour frame = new AssignmentFour();
frame.setTitle("Closest points");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setVisible(true);
}//main
class PointPanel extends JPanel {
private int xCoordinate = 200;
private int yCoordinate = 200;
private int radius = 5;
private Graphics g;
double minDist = 999999999;
ArrayList<Point> points = new ArrayList<>();
Point ClosestPoint1, ClosestPoint2;
public final double distBetweenPoints(int x, int y, int a, int b) {
double theDist = 0.0;
theDist = Math.sqrt(Math.pow(a - x, 2) + Math.pow(y - b, 2));
return theDist;
}//distBetweenPoints method
public PointPanel() {
addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
xCoordinate = e.getX();
yCoordinate = e.getY();
Point newCoord = e.getPoint();
points.add(newCoord);
g = getGraphics();
g.setColor(Color.RED);
g.drawOval(xCoordinate, yCoordinate, radius, radius);
//g.dispose();
if (points.size() >= 2) {
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
Point p = points.get(i);
Point q = points.get(j);
int x1 = p.x;
int y1 = p.y;
int a1 = q.x;
int b1 = q.y;
if (distBetweenPoints(x1, y1, a1, b1) < minDist) {
minDist = distBetweenPoints(x1, y1, a1, b1);
ClosestPoint1 = p;
ClosestPoint2 = q;
}//inner if
else {
}//else
}//for 'j'
}// for 'i'
int x2 = ClosestPoint1.x;
int y2 = ClosestPoint1.y;
int a2 = ClosestPoint2.x;
int b2 = ClosestPoint2.y;
g.fillOval(x2, y2, radius, radius);
g.fillOval(a2, b2, radius, radius);
}//if
}//mouseReleased
}//MouseListener
);
}//pointPanel
}//point panel extend
}//assignmentfour class