Java Reference
In-Depth Information
The Decrease Level button's event handler is registered in lines 60-80. Method
actionPerformed retrieves the current level of recursion and decrements it by 1 (lines 67-
68). Lines 71-72 ensure that the level is greater than or equal to MIN_LEVEL and less than
or equal to MAX_LEVEL —the fractal is not defined for recursion levels less than MIN_LEVEL
and you can't see the additional detail above MAX_LEVEL . You can go up to any desired
level, but around level 10 and higher, the fractal rendering becomes slow due to the details
to be drawn. Lines 74-76 reset the level label to reflect the change—the new level is set
and the repaint method is called to update the image to show the fractal at the new level.
The Increase Level JButton works like the Decrease Level JButton , but the level is
incremented rather than decremented to show more details of the fractal (lines 93-94).
When the application is first executed, the level will be set to 0, which will display a blue
line between two points that were specified in the FractalJPanel class.
Class FractalJPanel (Fig. 18.19) specifies the drawing JPanel 's dimensions as 400
by 400 (lines 13-14). The FractalJPanel constructor (lines 18-24) takes the current level
as a parameter and assigns it to its instance variable level . Instance variable color is set
to blue by default. Lines 22-23 change the JPanel 's background color to white (so the
fractal is easy to see), and set the drawing FractalJPanel 's dimensions.
1
// Fig. 18.19: FractalJPanel.java
2
// Drawing the "Lo feather fractal" using recursion.
3
import java.awt.Graphics;
4
import java.awt.Color;
5
import java.awt.Dimension;
6
import javax.swing.JPanel;
7
8
public class FractalJPanel extends JPanel
9
{
10
private Color color; // stores color used to draw fractal
11
private int level; // stores current level of fractal
12
13
private static final int WIDTH = 400 ; // defines width of JPanel
14
private static final int HEIGHT = 400 ; // defines height of JPanel
15
16
// set the initial fractal level to the value specified
17
// and set up JPanel specifications
18
public FractalJPanel( int currentLevel)
19
{
20
color = Color.BLUE ; // initialize drawing color to blue
21
level = currentLevel; // set initial fractal level
22
setBackground( Color.WHITE );
23
setPreferredSize( new Dimension( WIDTH , HEIGHT ));
24
}
25
26
// draw fractal recursively
public void drawFractal( int level, int xA, int yA, int xB,
int yB, Graphics g)
{
27
28
29
Fig. 18.19 | Drawing the “Lo feather fractal” using recursion. (Part 1 of 4.)
Search WWH ::




Custom Search