import java.awt.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class DrawPointsDemo {
public DrawPointsDemo() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 300);
f.setLocationRelativeTo(null);
ViewPanel viewPanel = new ViewPanel(createTestPoints());
f.add(viewPanel);
f.setVisible(true);
}
private List<FPoint> createTestPoints() {
List<FPoint> points = new ArrayList<FPoint>();
points.add(new FPoint(10, 10));
points.add(new FPoint(10, 100));
points.add(new FPoint(50, 80));
points.add(new FPoint(100, 200));
points.add(new FPoint(150, 250));
points.add(new FPoint(70, 260));
points.add(new FPoint(175, 175));
return points;
}
public static void main(final String[] args) {
Runnable gui = new Runnable() {
@Override
public void run() {
DrawPointsDemo newMain = new DrawPointsDemo();
}
};
SwingUtilities.invokeLater(gui);
}
}
class ViewPanel extends JPanel {
private List<FPoint> points;
public ViewPanel(List<FPoint> points) {
this.points = points;
}
@Override
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
resetVisited();
g.setColor(Color.BLUE);
FPoint p1 = getStartPoint();
FPoint p2 = getNextPoint(p1);
while (p2 != null) {
g.drawLine(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
p2 = getNextPoint(p1);
}
g.setColor(Color.RED);
for (final FPoint point : points) {
g.fillOval(point.x - 2, point.y - 2, 4, 4);
}
}
private FPoint getStartPoint() {
int yB = 0;
FPoint pB = null;
for (final FPoint point : points) {
if (!point.isVisited() && point.y > yB) {
yB = point.y;
pB = point;
}
}
if (pB != null) {
pB.setVisited(true);
}
return pB;
}
private FPoint getNextPoint(final FPoint p1) {
if(p1 == null){
throw new IllegalArgumentException("Argument must not be null");
}
FPoint pN = null;
double distanceN = Double.MAX_VALUE;
for (final FPoint point : points) {
if (!point.isVisited()) {
double distance = point.distance(p1);
if (distance < distanceN) {
distanceN = distance;
pN = point;
}
}
}
if (pN != null) {
pN.setVisited(true);
}
return pN;
}
private void resetVisited() {
for (final FPoint point : points) {
point.setVisited(false);
}
}
public List<FPoint> getPoints() {
return points;
}
public void setPoints(final List<FPoint> points) {
this.points = points;
repaint();
}
}
class FPoint extends Point {
private boolean visted;
public FPoint(final int x, final int y) {
super(x, y);
}
public boolean isVisited() {
return visted;
}
public void setVisited(final boolean visited) {
this.visted = visited;
}
}