Java Reference
In-Depth Information
Calling getValue() with the argument as the NAME key that is defined in the Action interface
returns the String object that was stored for the FileAction object when it was created. If the name
for the current object matches that of a particular FileAction object, then that must be the action to
which the event applies, so we know what to do. We have one if or else-if block for each action,
and we will code these one by one.
Many of these operations will involve dialogs. We need to get at the file system and display the list of
directories and files to choose from, for an Open operation for instance. It sounds like a lot of work, and
it certainly would be, if it weren't for a neat facility provided by the JFileChooser class.
Using a File Chooser
The JFileChooser class in the javax.swing package provides an easy to use mechanism for
creating file dialogs for opening and saving files. You can use a single object of this class to create all the
file dialogs you need, so add a member to the SketchFrame class to store a reference to a
JFileChooser object that we will create in the constructor:
private JFileChooser files; // File chooser dialog
There are several JFileChooser constructors but we will discuss just a couple of them here. The
default constructor creates an object with the current directory as the default directory but that won't
quite do for our purposes. What we want is for the default directory to be the DEFAULT _ DIRECTORY ,
which we defined in the Constants interface, so we'll use the constructor that accepts a File object
specifying a default directory to create a JFileChooser object in the SketchFrame constructor. Add
the following statement to the constructor following the statements that we added earlier that ensured
DEFAULT _ DIRECTORY actually existed on the hard drive:
files = new JFileChooser(DEFAULT _ DIRECTORY);
Any dialogs created by the files object will have DEFAULT _ DIRECTORY as the default directory that
is displayed. We can now use the files object to implement the event handling for the F ile menu.
There are a considerable number of methods in the JFileChooser class, so rather than trying to
summarize them all, which would take many pages of text and be incredibly boring, let's try out the
ones that we can apply to Sketcher to support the F ile menu.
File Save Operations
In most cases we will want to display a modal file save dialog when the S ave menu item or toolbar
button is selected. As luck would have it, the JFileChooser class has a method showSaveDialog()
that does precisely what we want. All we have to do is pass it a reference to the Component object that
will be the parent for the dialog to be displayed. The method returns a value indicating how the dialog
was closed. We could display a save dialog in a FileAction() method with the statement:
int result = files.showSaveDialog(SketchFrame.this);
Search WWH ::




Custom Search