Java Reference
In-Depth Information
We first check the
sketchChanged
flag. If the flag is
false
, either the sketch is empty, or it hasn't
been changed since the last save. Either way there's no point in writing it to disk, so we return
immediately. We then initialize the local variable,
file
, with the reference stored in
modelFile
. If
modelFile
was not
null
, then we skip the entire
if
and just call the
saveSketch()
method to
write the file to
modelFile
- we will get to the detail of the
saveSketch()
method in a moment.
The condition tested in the next
if
looks rather complicated but this is primarily due to the plethora of
arguments in the
showConfirmDialog()
call and we can break the condition down into its
component parts quite easily. There are two logical expressions separated by
||
so if either is
true
then we execute a
return
. The first expression just checks for
file
being
null
so if this is the case
we return immediately. If the first expression is
false
,
file
is not
null
and the second expression
will be evaluated.
This will be
true
if
file
references a file that does exist AND the value returned from the
showConfirmDialog()
method is
JOptionPane.NO
_
OPTION
. The dialog just warns of the
overwrite potential so if
JOptionPane.NO
_
OPTION
is returned then the user has elected not to
overwrite the file. Remember that with the
||
operator, if the left operand is
true
then the right
operand will not be evaluated. Similarly, with the
&&
operator, if the left operand is
false
then the
right operand will not be evaluated. This means that the
showConfirmDialog()
method will only be
executed if
file
is not
null
- so the left expression for the
||
is
false
- and
file
references a file
that does exist - so the left operand for the
&&
is
true
. If we don't execute the return, then we fall
through the
if
to call our helper method
saveSketch()
with
file
as the argument.
Writing a Sketch to a File
Writing a sketch to a file just means making use of what we learned about writing objects to a file. We
have already ensured that a
SketchModel
object is serializable, so we can write the sketch to an
ObjectOutputStream
with the following method in
SketchFrame
:
// Write a sketch to outFile
private void saveSketch(File outFile) {
try {
ObjectOutputStream out = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(outFile)));
out.writeObject(theApp.getModel()); // Write the sketch to the
// stream
out.close(); // Flush & close it
} catch(IOException e) {
System.err.println(e);
JOptionPane.showMessageDialog(SketchFrame.this,
"Error writing a sketch file.",
"File Output Error",
JOptionPane.ERROR
_
MESSAGE);
return; // Serious error - return
}
if(outFile != modelFile) { // If we are saving to a new file
// we must update the window
modelFile = outFile; // Save file reference
filename = modelFile.getName(); // Update the file name
setTitle(frameTitle + modelFile.getPath()); // Change the window title