Java Reference
In-Depth Information
How do you draw a Sierpinski triangle of order
1
? The problem can be reduced to drawing
three Sierpinski triangles of order
0
. How do you draw a Sierpinski triangle of order
2
? The
problem can be reduced to drawing three Sierpinski triangles of order
1
, so the problem of
drawing a Sierpinski triangle of order
n
can be reduced to drawing three Sierpinski triangles
of order
n - 1
.
Listing 20.9 gives a Java applet that displays a Sierpinski triangle of any order, as shown in
Figure 20.9. You can enter an order in a text field to display a Sierpinski triangle of the spec-
ified order.
L
ISTING
20.9
SierpinskiTriangle.java
1
import
javax.swing.*;
2
import
java.awt.*;
3
import
java.awt.event.*;
4
5
public class
SierpinskiTriangle
extends
JApplet {
6
private
JTextField jtfOrder =
new
JTextField(
"0"
,
5
);
// Order
7
private
SierpinskiTrianglePanel trianglePanel =
8
new
SierpinskiTrianglePanel();
// To display the pattern
9
10
public
SierpinskiTriangle() {
11
// Panel to hold label, text field, and a button
12 JPanel panel =
new
JPanel();
13 panel.add(
new
JLabel(
"Enter an order: "
));
14 panel.add(jtfOrder);
15 jtfOrder.setHorizontalAlignment(SwingConstants.RIGHT);
16
17
// Add a Sierpinski triangle panel to the applet
18 add(trianglePanel);
19 add(panel, BorderLayout.SOUTH);
20
21
// Register a listener
22
23 @Override
24
public void
actionPerformed(ActionEvent e) {
25 trianglePanel.setOrder(Integer.parseInt(jtfOrder.getText()));
26 }
27 });
28 }
29
30
jtfOrder.addActionListener(
new
ActionListener() {
listener
set a new order
static class
SierpinskiTrianglePanel
extends
JPanel {
31
private int
order =
0
;
32
33
/** Set a new order */
34
public void
setOrder(
int
order) {
35
this
.order = order;
36 repaint();
37 }
38
39 @Override
40
protected void
paintComponent(Graphics g) {
41
super
.paintComponent(g);
42
43
// Select three points in proportion to the panel size
44
45
46
47
Point p1 =
new
Point(getWidth() /
2
,
10
);
three initial points
Point p2 =
new
Point(
10
, getHeight() -
10
);
Point p3 =
new
Point(getWidth() -
10
, getHeight() -
10
);