Java Reference
In-Depth Information
30
// base case: draw a line connecting two given points
if
(level ==
0
)
g.drawLine(xA, yA, xB, yB);
else
// recursion step: determine new points, draw next level
{
// calculate midpoint between (xA, yA) and (xB, yB)
int
xC = (xA + xB) /
2
;
int
yC = (yA + yB) /
2
;
// calculate the fourth point (xD, yD) which forms an
// isosceles right triangle between (xA, yA) and (xC, yC)
// where the right angle is at (xD, yD)
int
xD = xA + (xC - xA) /
2
- (yC - yA) /
2
;
int
yD = yA + (yC - yA) /
2
+ (xC - xA) /
2
;
// recursively draw the Fractal
drawFractal(level -
1
, xD, yD, xA, yA, g);
drawFractal(level -
1
, xD, yD, xC, yC, g);
drawFractal(level -
1
, xD, yD, xB, yB, g);
}
}
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// start drawing the fractal
53
@Override
54
public
void
paintComponent(Graphics g)
55
{
56
super
.paintComponent(g);
57
58
// draw fractal pattern
59
g.setColor(color);
60
drawFractal(level,
100
,
90
,
290
,
200
, g);
61
}
62
63
// set the drawing color to c
64
public
void
setColor(Color c)
65
{
66
color = c;
67
}
68
69
// set the new level of recursion
70
public
void
setLevel(
int
currentLevel)
71
{
72
level = currentLevel;
73
}
74
75
// returns level of recursion
76
public
int
getLevel()
77
{
78
return
level;
79
}
80
}
// end class FractalJPanel
Fig. 18.19
|
Drawing the “Lo feather fractal” using recursion. (Part 2 of 4.)