Java Reference
In-Depth Information
You use this object when you implement file operations for a sketch.
NOTE
There is a
java.io.FileFilter
interface that is easily confused with the
javax.swing.filechooser.FileFilter
class, especially if you make use of
*
to import all
the names in a package.
Querying a File Chooser Dialog
You obviously need to be able to discover which file or directory the user selected in the dialog. When the
dialog is closed with the approve button, you can call
getSelectedFile()
for the dialog object. This re-
turns the file as a
File
object. You don't need it for Sketcher, but if you have enabled multiple selections in
the dialog, calling the
getSelectedFiles()
method for the dialog object returns an array of
File
objects
corresponding to the selected files.
That's enough detail on the
JFileChooser
class for now. Let's return to what you need to implement in
Sketcher for File menu operations.
IMPLEMENTING FILE OPERATIONS
You need to implement the capability to respond to events for the Save, Save As, and New menu items in the
File menu. Although these are independent operations, they have quite a lot of function in common. Where
a dialog is required, it is a
JFileChooser
dialog customized to the requirements of a given operation. Let's
implement a customized file dialog capability in Sketcher first of all.
Creating a Customized File Dialog
You can add a method to the
SketcherFrame
class to display a customized file dialog and return a
String
object encapsulating the path for the file that has been selected:
// Display a custom file dialog
private Path showDialog(String dialogTitle,
String approveButtonText,
String approveButtonTooltip,
ExtensionFilter filter,
Path file) {
// Current file path - if any
fileChooser.setDialogTitle(dialogTitle);
fileChooser.setApproveButtonText(approveButtonText);
fileChooser.setApproveButtonToolTipText(approveButtonTooltip);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.addChoosableFileFilter(filter);
// Add the filter
fileChooser.setFileFilter(filter);
// and select it