Java Reference
In-Depth Information
How It Works
After dealing with saving the current sketch in the actionPerformed() member of the FileAction
class, we use our showDialog() method that we defined in the SketchFrame class to display a file
open dialog. Our showDialog() method is all-purpose - we can put any kind of label on the button or
title in the title bar so we can use it to display any of the dialogs we need for file operations.
If a File object was selected in the dialog, we pass this to the openSketch() member of
SketchFrame to read a new sketch from the file. The openSketch() method creates an
ObjectInputStream object from the File object passed as an argument, and reads a SketchModel
object from the stream by calling the readObject() method. The object returned by the
readObject() method has to be cast to the appropriate type - SketchModel in our case. We pass
this SketchModel object to the insertModel() method for the application object. This replaces the
current sketch reference in the sketch member of the application object with a reference to the new
sketch, and then sets the view and the application window as observers. Calling repaint() for the
view object displays the new sketch, since the paint() method for the view object obtains a reference
to the current model by calling the getModel() member of the application object, which will return
the reference to the new model.
Starting a New Sketch
The Fi le | New menu item simply starts a new sketch. This is quite similar to the open operation except
that we must create an empty sketch rather than read a new one from disk. The processes of checking
for the need to save the current sketch and inserting the new SketchModel object into the application
will be the same.
Try It Out - Implementing the New Operation
We need to place the code to do this in the else - if block corresponding to the newAction object
event. This is in the code in the actionPerformed() method in the FileAction class:
else if(name.equals(newAction.getValue(NAME))) {
checkForSave();
theApp.insertModel(new SketchModel()); // Insert new empty sketch
modelFile = null; // No file for it
filename = DEFAULT _ FILENAME; // Default name
setTitle(frameTitle + files.getCurrentDirectory() +
"\\" + filename);
sketchChanged = false; // Not changed yet
}
Now you can create a new sketch.
How It Works
All the saving of the existing sketch is dealt with by our checkForSave() method. The new part is the
last five lines of code. We call the SketchModel constructor to create a new empty sketch, and pass it
to the insertModel() method for the application object. This will insert the new sketch into the
application and get the view object to display it. We then update the data members of the window that
record information about the file for the current sketch and its status. We also set the sketchChanged
flag to false as it's an empty sketch.
Search WWH ::




Custom Search