Java Reference
In-Depth Information
You need to place the code to create a new empty sketch in the
else-if
block corresponding to the
newAction
object event. This is in the
actionPerformed()
method in the
FileAction
inner class:
else if(this == newAction) {
checkForSave();
theApp.insertModel(new SketcherModel());
// Insert new
empty sketch
currentSketchFile = null;
// No file for it
setTitle(frameTitle);
sketchChanged = false;
// Not changed yet
return;
}
Directory "Sketcher 4 creating a new sketch"
With this addition to Sketcher you can create a new sketch.
How It Works
All the saving of the existing sketch is dealt with by the
checkForSave()
method that you added to the
SketcherFrame
class. The new part is the last five lines of the highlighted code. You call the
Sketch-
erModel
constructor to create a new empty sketch, and pass it to the
insertModel()
method for the
application object. This inserts the new sketch into the application and gets the view object to display it.
You then update the data members of the window that record information about the file for the current
sketch and its status. You also set the
sketchChanged
flag to
false
, as it's an empty sketch.
Preventing Data Loss on Close
At the moment, the application shuts down immediately when you click the window close icon. This means
you could lose hours of work in an instant if you forget to save the sketch. But the solution is very simple.
You just need to get the event handler for the window closing event to call the
checkForSave()
method for
the window object.
TRY IT OUT: Prompting for Save on Close
To implement this you can use the
WindowListener
object for the application window that you have
already added in the
Sketcher
class. This listener receives notification of events associated with opening
and closing the window, as well as minimizing and maximizing it. You just need to add some code to the
body of the
windowClosing()
method for the listener. You require one extra line in the Sketcher class
definition: