Java Reference
In-Depth Information
public class SketcherFrame extends JFrame {
// Constructor
public SketcherFrame(String title) {
setTitle(title); // Set the window title
setJMenuBar(menuBar); // Add the menu bar to the
window
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Default is exit the
application
createFileMenu();
// Create the File menu
createElementMenu();
// Create the element menu
createColorMenu();
// Create the color menu
}
// You will add helper methods that create Action objects here...
// You will add helper methods that create the menus here...
// You will add inner classes that define action objects here...
// You will add action objects as members here...
private JMenuBar menuBar = new JMenuBar(); // Window menu bar
// You will add members to store menubar menus here...
private Color elementColor = DEFAULT_ELEMENT_COLOR; // Current element color
private int elementType = DEFAULT_ELEMENT_TYPE; // Current element type
}
Directory "Sketcher 6 using Action objects"
In the previous version of Sketcher, Color was a submenu of Elements. This was useful in demonstrating
how you create a submenu, but color has no particular connection to the type of element, so perhaps it would
be better with Color as an independent menu item on the menu bar in the new version. The three method
calls in the constructor create the menus.
You have restored the statement to set the default close operation as
EXIT_ON_CLOSE
, so you won't need
to call
dispose()
and
exit()
in the window event handler. Now would be a good time to delete the state-
ments from the
windowClosing()
method in the inner
WindowHandler
class to the
Sketcher
class. The old
inner classes in
SketcherFrame
have been deleted, as well as the fields storing references to menu items.
All the code to create the menu items has been wiped as well, along with the code that added the listeners.
You are ready to begin reconstruction. You
can
rebuild it! Stronger! Faster! Invincible!
Defining Action Classes
You need three inner classes defining actions: one for the
File
menu items, another for the element
type menu items, and the third for element colors. You derive each of these classes from the
javax.swing.AbstractAction
class that already implements the
Action
interface. The
AbstractAction
class has three constructors. The no-arg constructor creates an object with a default name and icon. You can
supply just a name argument as type
String
, and you get a default icon. Finally you can supply both a name
and an icon as type
Icon
.