Java Reference
In-Depth Information
"Save the sketch",
's',
modelFile == null ? new File(
files.getCurrentDirectory(),
filename):modelFile);
if(file != null) {
if(file.exists() && !file.equals(modelFile))
if(JOptionPane.NO _ OPTION == // Overwrite warning
JOptionPane.showConfirmDialog(SketchFrame.this,
file.getName()+" exists. Overwrite?",
"Confirm Save As",
JOptionPane.YES _ NO _ OPTION,
JOptionPane.WARNING _ MESSAGE))
return; // No file selected
saveSketch(file);
}
return;
}
Recompile with these additions and you will have a working Save As ... option on the F ile menu, with a
file filter in action too!
How It Works
Most of this is under the S ave menu operation. We have a fancy expression as the last argument to the
showDialog() method. This is because the Save As… operation could be with a sketch that has been
saved previously, or with a sketch that has never been saved. The expression passes modelFile as the
argument if it is not null , and creates a new File object as the argument from the current directory
and file name if it is. If we get a non-null File object back from the showDialog() method, then we
check for a potential overwrite of an existing file. This will be the case if the selected file exists and is
also different from modelFile . In this instance we display a YES/NO dialog warning of this just to
ensure that overwriting the existing file is intended. If the user closes the dialog by selecting the No
button, we just return, otherwise we save the current sketch in the file.
Since we have sketches written to disk, let's now look at how we can implement the operation for the
Open menu item so we can try reading them back.
File Open Operations
Supporting the file/open operation is in some ways a little more complicated than save. We have to
consider the currently displayed sketch first of all. Opening a new sketch will replace it, so does it need
to be saved before the file open operation? If it does, we must deal with that before we can read a new
sketch from the file. Fortunately, most of this is already done by our saveOperation() method. We
just need to add a prompt for the save operation when necessary. We could put this in a
checkForSave() method that we can implement in the SketchFrame class as:
// Prompt for save operation when necessary
public void checkForSave() {
if(sketchChanged)
if(JOptionPane.YES _ OPTION ==
Search WWH ::




Custom Search