Java Reference
In-Depth Information
31
32
/** Returns true if the point is inside an existing circle */
33
private boolean isInsideACircle(Point2D p) {
34
for (Node circle: this .getChildren())
35
if (circle.contains(p))
contains the point?
36
return true ;
37
38
return false ;
39 }
40
41
/** Color all circles if they are connected */
42
private void colorIfConnected() {
43
if (getChildren().size() == 0 )
44
return ; // No circles in the pane
45
46 // Build the edges
47 java.util.List<AbstractGraph.Edge> edges
48 = new java.util.ArrayList<>();
49 for ( int i = 0 ; i < getChildren().size(); i++)
50 for ( int j = i + 1 ; j < getChildren().size(); j++)
51 if (overlaps((Circle)(getChildren().get(i)),
52 (Circle)(getChildren().get(j)))) {
53 edges.add( new AbstractGraph.Edge(i, j));
54 edges.add( new AbstractGraph.Edge(j, i));
55 }
56
57 // Create a graph with circles as vertices
58 Graph<Node> graph = new UnweightedGraph<>
59 ((java.util.List<Node>)getChildren(), edges);
60 AbstractGraph<Node>.Tree tree = graph.dfs( 0 ); // a DFS tree
61 boolean isAllCirclesConnected = getChildren().size() == tree
62 .getNumberOfVerticesFound();
63
64 for (Node circle: getChildren()) {
65 if (isAllCirclesConnected) { // All circles are connected
66 ((Circle)circle).setFill(Color.RED);
67 }
68 else {
69 ((Circle)circle).setStroke(Color.BLACK);
70 ((Circle)circle).setFill(Color.WHITE);
71 }
72 }
73 }
74 }
75
76 public static boolean overlaps(Circle circle1, Circle circle2) {
77 return new Point2D(circle1.getCenterX(), circle1.getCenterY()).
78 distance(circle2.getCenterX(), circle2.getCenterY())
79 <= circle1.getRadius() + circle2.getRadius();
80 }
81 }
create edges
create a graph
get a search tree
connected?
connected
not connected
two circles overlap?
The JavaFX Circle class contains the data fields x , y , and radius , which specify the
circle's center location and radius. It also defines the contains for testing if a point is in the
circle. The overlaps method (lines 76-80) checks whether two circles overlap.
When the user clicks the mouse outside of any existing circle, a new circle is created cen-
tered at the mouse point and the circle is added to the pane (line 26).
To detect whether the circles are connected, the program constructs a graph (lines 46-59).
The circles are the vertices of the graph. The edges are constructed in lines 49-55. Two circle
 
Search WWH ::




Custom Search