Java Reference
In-Depth Information
By adding new Action classes for our two new menu items, we avoid cluttering up the existing
FileAction class any further. Clearly, a lot of the work will be in the implementation of the new Action
classes, so let's start with the easy bit - adding the new menu items to the F ile menu. First, we can add two
new fields for the menu items by changing the existing definition in the SketchFrame class:
private FileAction newAction, openAction, closeAction,
saveAction, saveAsAction, printAction;
private XMLExportAction exportAction; // Stores action for XML export menu item
private XMLImportAction importAction; // Stores action for XML import menu item
These store the references to the Action objects for the new menu items.
We can add the menu items in the SketchFrame constructor, immediately following the menu
separator definition that comes after the saveAsAction menu item:
addMenuItem(fileMenu, saveAction);
addMenuItem(fileMenu, saveAsAction);
fileMenu.addSeparator(); // Add separator
addMenuItem(fileMenu,
exportAction = new XMLExportAction("Export XML",
"Export sketch as an XML file"));
addMenuItem(fileMenu,
importAction = new XMLImportAction("Import XML",
"Import sketch from an XML file"));
fileMenu.addSeparator(); // Add separator
Now we can add code in the SketchFrame class for the two inner classes. We can define the
ExportAction class within the SketchFrame class like this:
class XMLExportAction extends AbstractAction {
public XMLExportAction(String name, String tooltip) {
super(name);
if(tooltip != null) // If there is tooltip text
putValue(SHORT _ DESCRIPTION, tooltip); // ...squirrel it away
}
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser(DEFAULT _ DIRECTORY);
chooser.setDialogTitle("Export Sketch as XML");
chooser.setApproveButtonText("Export");
ExtensionFilter xmlFiles = new ExtensionFilter(".xml",
"XML Sketch files (*.xml)");
chooser.addChoosableFileFilter(xmlFiles); // Add the filter
chooser.setFileFilter(xmlFiles); // and select it
int result = chooser.showDialog(SketchFrame.this, null); // Show dialog
File file = null;
if(chooser.showDialog(SketchFrame.this, null) == chooser.APPROVE _ OPTION){
file = chooser.getSelectedFile();
if(file.exists()) { // Check file exists
if(JOptionPane.NO _ OPTION == // Overwrite warning
Search WWH ::




Custom Search