Java Reference
In-Depth Information
start with the easy bit — adding the new menu items to the File menu. First, you can add two new fields for
the menu items by changing the existing definition in the
SketcherFrame
class:
private FileAction newAction, openAction, closeAction,
saveAction, saveAsAction, printAction,
exportAction, importAction, exitAction;
You can create the
Action
objects for the two new menu items in the
createFileMenuActions()
meth-
od, following the creation of the
Action
item for the Print menu item:
printAction = new FileAction("Print", 'P', CTRL_DOWN_MASK);
exportAction = new FileAction("Export XML", 'E', CTRL_DOWN_MASK);
importAction = new FileAction("Import XML", 'I', CTRL_DOWN_MASK);
exitAction = new FileAction("Exit", 'X', CTRL_DOWN_MASK);
The new fields store references to the
Action
objects for the new menu items. You don't need to add
these to the
actions
array definition because you use the array to create toolbars for corresponding menu
items and you won't be adding toolbar buttons for the XML I/O operations.
You can add the
SHORT_DESCRIPTION
property values for the new
Action
objects in the
cre-
ateFileMenuActions()
method, where it does this for the other
Action
objects:
exportAction.putValue(SHORT_DESCRIPTION, "Export sketch as an XML file");
importAction.putValue(SHORT_DESCRIPTION, "Import sketch from an XML file");
You can add the menu items to the File menu in the
createFileMenu()
method, immediately before the
statement adding the separator that precedes the
exitAction
:
fileMenu.addSeparator(); // Add separator
fileMenu.add(exportAction); // Export XML menu item
fileMenu.add(importAction); // Import XML menu item
fileMenu.addSeparator(); // Add separator
fileMenu.add(exitAction); // Print sketch menu item
menuBar.add(fileMenu); // Add the file menu
Next you can add an extra
else if
block in the
actionPerformed()
method in the
FileAction
class
to respond to events from the new menu items:
public void actionPerformed(ActionEvent e) {
// Code for if statement as before...
} else if(this == exitAction) {
// Code to handle exitAction event as before...
} else if(this == exportAction) {
exportXMLOperation();
// Export sketch as XML
} else if(this == importAction) {
importXMLOperation();
// Import an XML sketch
}
}
The
exportXMLOperation()
method you add to the
SketcherFrame
class takes care of handling events
for the Export XML menu item, and the
importXMLOperation()
method deals with events for the Import
XML menu item.