Java Reference
In-Depth Information
return(result == files.APPROVE
_
OPTION) ? files.getSelectedFile() : null;
}
Now when you display a file save dialog, it will use the Sketcher file filter by default, and will only
display directories or files with the extension
.ske
. The user can override this by selecting the
All Files
option in the dialog, whereupon all files in the current directory will be displayed.
How It Works
The file filter,
sketchFilter
, that we create is added to the list of available filters in the
JFileChooser
object by passing a reference to the
addChoosableFileFilter()
method. We
then set this filter as the one in effect by calling the
setFileFilter()
method. The
JFileChooser
object will check each file in the file list by passing a
File
object to the
accept()
method for our file
filter object. This will only return
true
for directories or files with the extension
.ske
. The description
of the filter is obtained by the
JFileChooser
object calling the
getDescription()
method in the
Sketcher
FileFilter
class and displaying it in the dialog.
Of course, the available list of file filters will include the 'accept all' filter that is there by default. You
might want to suppress this in some situations and there is a method defined in the
JFileChooser
class to do this:
files.setAcceptAllFileFilter(false); // Remove 'all files' filter
Of course, passing an argument of
true
to this method will restore the filter to the list. You can also
discover whether the all files filter is used by calling the
isAcceptAllFileFilterUsed()
method,
which will return
true
if it is and
false
otherwise.
You can also remove specific
FileFilter
objects from the list maintained by the
JFileChooser
object. Just pass a
FileFilter
reference to the
removeChoosableFileFilter()
method for your
file chooser, for example:
files.removeChoosableFileFilter(sketchFilter); // removes our filter
This would remove the filter we have defined for Sketcher files.
File Save As Operations
For save as... operations, we will always display a save dialog, regardless of whether the file has been saved
before and ignoring the state of the dirty flag. Apart from that and some cosmetic differences in the dialog
itself, the operation is identical to the
S
ave
menu item event handling. With the
showDialog()
method
available in the
SketchFrame
class, the implementation becomes almost trivial.
Try It Out - File Save As Operations
The code in the
else
if
block in
actionPerformed()
for this operation will be:
else if(name.equals(saveAsAction.getValue(NAME))) {
File file = showDialog("Save Sketch As",
"Save",