Java Reference
In-Depth Information
If the selected file does not exist, or if it exists but is not the same as the current file, or if it exists and is
the same as the current file and YES was selected in the warning dialog, you want to write the sketch to
the file. Thus if any of the three operands are
false
, you save the current sketch in the file.
Because you can record sketches in files, you are ready to look at implementing the operation for the
Open menu item where you read them back.
Implementing the File Open Operation
Supporting the file open operation is in some ways a little more complicated than save. You have to consider
the currently displayed sketch, first of all. Opening a new sketch replaces it, so does it need to be saved
before the file open operation? If it does, you must deal with that before you can read a new sketch from
the file. Fortunately, most of this is already done by the
saveOperation()
method that you have implemen-
ted in the
SketcherFrame
class. You just need to add a prompt for the save operation when necessary. You
could put this in a
checkForSave()
method that you can implement in the
SketcherFrame
class as:
// Prompt for save operation when necessary for File Open
public void checkForSave() {
if(sketchChanged && JOptionPane.YES_OPTION ==
JOptionPane.showConfirmDialog(this,
"Current file has changed. Save current file?",
"Confirm Save Current File",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE)) {
saveOperation();
}
}
Directory "Sketcher 3 opening sketch files"
This method will be useful outside the
SketcherFrame
class a little later on, so you have defined it as a
public
member of the class. If the
sketchChanged
flag is
true
, the expression that is the right operand for
the
&&
operator is evaluated. This pops up a confirmation dialog to verify that the sketch needs to be saved.
If it does, you call the
saveOperation()
method to do just that. Of course, if
sketchChanged
has the value
false
, the right operand to the
&&
operator is not evaluated, and so the dialog isn't displayed.
When you get to the point of reading a sketch from the file, some further complications arise. You must
replace the existing
SketcherModel
object and its view in the application with a new
SketcherModel
ob-
ject and its view.
With those few thoughts, you should be ready to make it happen.
TRY IT OUT: Implementing the Open Menu Item Operation