Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 14 ■ RECURSION

exitItem.setMnemonic('x');
exitItem.addActionListener(this);
file.add(exitItem);
JMenuItem redrawItem = new JMenuItem("Repaint");
redrawItem.setMnemonic('r');
redrawItem.addActionListener(this);
file.add(redrawItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(file);
frame.setJMenuBar(menuBar);
}


private void createAndShowGUI() {
addMenu(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sierpinskiTrianglePanel.setPreferredSize(new Dimension(400, 400));
sierpinskiTrianglePanel.setBackground(Color.WHITE);
frame.getContentPane().add(sierpinskiTrianglePanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SierpinskiTriangle sierpinskiTriangle = new SierpinskiTriangle();
sierpinskiTriangle.createAndShowGUI();
}


public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() != null) {
if (e.getActionCommand().equals("Exit")) {
System.exit(0);
}
if (e.getActionCommand().equals("Repaint")) {
sierpinskiTrianglePanel.repaint();
}
}
}
}


By now, you're accustomed to how this kind of program class works: it handles the input from the
user, sets up the window that holds your content, and manages the class that does the more interesting
work.
Here's the class that does the drawing:


Listing 14-5. SierpinskiTrianglePanel.java


package com.bryantcs.examples.fractals;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.geom.Point2D;

Free download pdf