Java Reference
In-Depth Information
displayTriangles(g, order, p1, p2, p3);
48
49 }
50
51
52
53
if
(order ==
0
) {
54
// Draw a triangle to connect three points
55 g.drawLine(p1.x, p1.y, p2.x, p2.y);
56 g.drawLine(p1.x, p1.y, p3.x, p3.y);
57 g.drawLine(p2.x, p2.y, p3.x, p3.y);
58 }
59
else
{
60
// Get the midpoint on each edge of the triangle
61 Point p12 = midpoint(p1, p2);
62 Point p23 = midpoint(p2, p3);
63 Point p31 = midpoint(p3, p1);
64
65
private static void
displayTriangles(Graphics g,
int
order,
Point p1, Point p2, Point p3) {
draw a triangle
// Recursively display three triangles
displayTriangles(g, order -
1
, p1, p12, p31);
top subtriangle
left subtriangle
right subtriangle
66
67
68
69 }
70 }
71
72
displayTriangles(g, order -
1
, p12, p2, p23);
displayTriangles(g, order -
1
, p31, p23, p3);
private static
Point midpoint(Point p1, Point p2) {
73
return new
Point((p1.x + p2.x) /
2
, (p1.y + p2.y) /
2
);
74 }
75 }
76 }
main method omitted
The initial triangle has three points set in proportion to the panel size (lines 44-46). If
order == 0
, the
displayTriangles(g, order, p1, p2, p3)
method displays a
triangle that connects the three points
p1
,
p2
, and
p3
in lines 55-57, as shown in
Figure 20.10a. Otherwise, it performs the following tasks:
displayTriangle
method
1. Obtain the midpoint between
p1
and
p2
(line 61), the midpoint between
p2
and
p3
(line
62), and the midpoint between
p3
and
p1
(line 63), as shown in Figure 20.10b.
2. Recursively invoke
displayTriangles
with a reduced order to display three smaller
Sierpinski triangles (lines 66-68). Note that each small Sierpinski triangle is struc-
turally identical to the original big Sierpinski triangle except that the order of a small
triangle is one less, as shown in Figure 20.10b.
A Sierpinski triangle is displayed in a
SierpinskiTrianglePanel
. The
order
property in
the inner class
SierpinskiTrianglePanel
specifies the order for the Sierpinski triangle.
The
Point
class, introduced in Section 16.8, Mouse Events, represents a point on a compo-
nent. The
midpoint(Point p1, Point p2)
method returns the midpoint between
p1
and
p2
(lines 72-74).
20.20
How do you obtain the midpoint between two points?
20.21
What is the base case for the
displayTriangles
method?
20.22
How many times is the
displayTriangles
method invoked for a Sierpinski triangle
of order 0, order 1, order 2, and order n?
✓
✓
Check
Point