Java Reference
In-Depth Information
JOptionPane.showConfirmDialog(SketchFrame.this,
"Current file has changed. Save current file?",
"Confirm Save Current File",
JOptionPane.YES
_
NO
_
OPTION,
JOptionPane.WARNING
_
MESSAGE))
saveOperation();
}
This will be useful outside the
SketchFrame
class a little later on, so we have declared it as a public
class member. If the
sketchChanged
flag is
true
, we pop up a confirm dialog to verify that the
sketch needs to be saved. If it does, we call the
saveOperation()
method to do just that.
When we get to the point of reading a sketch from the file, some further slight complications arise. We
must replace the existing
SketchModel
object and its view in the application with a new
SketchModel
object and its view.
With those few thoughts, we are now ready to make it happen.
Try It Out - Implementing the Open Menu Item Operation
The file open process will be similar to a save operation, but instead of writing the file, it will read it.
We'll add a helper method
openSketch()
to
SketchFrame
that, given a
File
object, will do the
reading. Using this method, the code to handle the
Open
menu item event will be:
} else if(name.equals(openAction.getValue(NAME))) {
checkForSave();
// Now open a sketch file
File file = showDialog(
"Open Sketch File", // Dialog window title
"Open", // Button lable
"Read a sketch from file", // Button tooltip text
'o', // Shortcut character
null); // No file selected
if(file != null) // If a file was selected
openSketch(file); // then read it
}
We can implement the
openSketch()
method in the
SketchFrame
class as:
// Method for opening file
public void openSketch(File inFile) {
try {
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(
new FileInputStream(inFile)));
theApp.insertModel((SketchModel)in.readObject());
in.close();
modelFile = inFile;
filename = modelFile.getName(); // Update the file name
setTitle(frameTitle+modelFile.getPath()); // Change the window title
sketchChanged = false; // Status is unchanged