Java Reference
In-Depth Information
The return value from the showDialog() member of the JFileChooser object files determines
whether the approve button was selected or not. If it was, we return the File object from the file chooser
that represents the selected file, otherwise we return null . A method calling our showDialog() method
can determine whether or not a file was chosen by testing the return value for null .
We can now use this method when we implement handling of a S ave menu item action event. A save
operation is a little more complicated than you might imagine at first sight, so let's consider it in a little
more detail.
Implementing the Save Operation
First of all, what happens in a save operation should depend on whether the current file has been saved
before. If it has, the user won't want to see a dialog every time. Once it has been saved the first time, the
user will want it written away without displaying the dialog. We can use the modelFile member of the
SketchFrame class to determine whether we need to display a dialog or not. We added this earlier to
hold a reference to the File object for the sketch. Before a sketch has been saved this will be null ,
and if it is not null we don't want to show the dialog. When the sketch has been saved, we will store a
reference to the File object in modelFile so this will generally hold a reference to the file holding
the last version of the sketch that was saved.
Secondly, if the sketch is unchanged - indicated by the sketchChanged member being false -
either because it is new and therefore empty or because it hasn't been altered since it was last saved, we
really don't need to save it at all.
We can package up these checks for when we need to save and when we display the dialog in another
method in the SketchFrame class. We'll call it saveOperation() , and make it a private member
of the SketchFrame class:
// Save the sketch if it is necessary
private void saveOperation() {
if(!sketchChanged)
return;
File file = modelFile;
if(file == null) {
file = showDialog("Save Sketch",
"Save",
"Save the sketch",
's',
new File(files.getCurrentDirectory(), filename));
if(file == null || (file.exists() && // Check for existence
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 selected file
}
saveSketch(file);
}
Search WWH ::




Custom Search