Java Reference

In-Depth Information

â–
Note
Fibonacci numbers turn up in all kinds of interesting places. They are closely linked to the golden ratio

(important in the history of art and architecture), appear in the ratios of a number of objects in nature, and have

been used to determine when to buy stocks. While they are well beyond the scope of this topic, the origin and uses

of the Fibonacci sequence are interesting subjects in their own right.

Calculating Fractals

Fractal images involve using the output of one calculation as the input to a subsequent calculationâ€”a

perfect task for recursion. I'll start with my personal favorite.

Drawing a Sierpinski Triangle

A Sierpinski triangle (named after Polish mathematician Waclaw Sierpinski) is a triangle consisting of

other triangles. Each smaller triangle can itself consist of other triangles. Thus, you can have triangles

within triangles within triangles to any depth you like. (Note the recursion within the preceding

sentence; just talking about recursion requires recursion.)

Here's a pair of classes that draw a Sierpinski triangle to a depth of 7 (a number I picked because I

liked the resulting output). As usual, I've created a program class that uses another class to do the

drawing.

Here's the program class:

Listing 14-4. SierpinskiTriangle.java

package com.bryantcs.examples.fractals;

import java.awt.Color;

import java.awt.Dimension;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

public class SierpinskiTriangle implements ActionListener {

private SierpinskiTrianglePanel

sierpinskiTrianglePanel = new SierpinskiTrianglePanel();

private JFrame frame = new JFrame("Sierpinski Triangle");

private void addMenu(JFrame frame) {

JMenu file = new JMenu("File");

file.setMnemonic('F');

JMenuItem exitItem = new JMenuItem("Exit");