// Class definition for LineSegment import java.awt.*; import java.util.*; public class LineSegment { LSPoint p1, p2; int id; LineSegmentCollection collection; Vector intersections; public LSPoint getP1() { return p1; } public LSPoint getP2() { return p2; } public LineSegment(int anID, LineSegmentCollection theCollection) { id = anID; collection = theCollection; p1 = new LSPoint(); p2 = new LSPoint(); computeIntersections(); } public void paint(Graphics g) { g.drawLine(p1.getX(), p1.getY(), p2.getX(), p2.getY()); plotIntersections(g); } public void computeIntersections() { intersections = new Vector(); for (Enumeration segments = (collection.otherSegments(this)).elements(); segments.hasMoreElements();) { LineSegment aLineSeg = (LineSegment) segments.nextElement(); LSPoint p = segIntersection(aLineSeg); //System.out.println("Intersection of lines is: (" + p.getX() // + ", " + p.getY() + ")" ); if (p != null) intersections.addElement(p); } } private LSPoint segIntersection(LineSegment ls) { LSPoint p3 = ls.getP1(); LSPoint p4 = ls.getP2(); int x1 = p1.getX(); int y1 = p1.getY(); int x2 = p2.getX(); int y2 = p2.getY(); int x3 = p3.getX(); int y3 = p3.getY(); int x4 = p4.getX(); int y4 = p4.getY(); double d1 = (x1 * y2) - (x2 * y1); double d2 = (x3 * y4) - (x4 * y3); double d3 = ((x1 - x2) * (y3 - y4)) - ((x3 - x4) * (y1 - y2)); int x = (int) (((d1 * (x3 - x4)) - (d2 * (x1 - x2))) / d3); int y = (int) (((d1 * (y3 - y4)) - (d2 * (y1 - y2))) / d3); int minx1 = Math.min(x1, x2); if (x < minx1) return null; int maxx1 = Math.max(x1, x2); if (x > maxx1) return null; int miny1 = Math.min(y1, y2); if (y < miny1) return null; int maxy1 = Math.max(y1, y2); if (y > maxy1) return null; int minx2 = Math.min(x3, x4); if (x < minx2) return null; int maxx2 = Math.max(x3, x4); if (x > maxx2) return null; int miny2 = Math.min(y3, y4); if (y < miny2) return null; int maxy2 = Math.max(y3, y4); if (y > maxy2) return null; return new LSPoint(x, y); } private void plotIntersections(Graphics g) { for (Enumeration intPoints = intersections.elements(); intPoints.hasMoreElements();) { LSPoint p = (LSPoint) intPoints.nextElement(); int x = p.getX(); int y = p.getY(); int radius = 5; g.fillOval(x - radius, y - radius, 2 * radius, 2 * radius); } } }