Java Reference
In-Depth Information
We now have a name assigned to the document, but there's another point to consider if we're preparing
to store a sketch. When we close the application, we should have a means of checking whether the
document needs to be saved. Otherwise it will be all too easy to close Sketcher and lose the brilliant
sketch that we have just spent three hours crafting. Checking whether the sketch needs to be saved isn't
difficult. We just need to record the fact that the document has changed.
Try It Out - Recording Changes to a Sketch
To provide the means of recording whether a sketch has been changed or not we can add a boolean
data member to the SketchFrame class that we will set to true when the SketchModel object
changes, and false when it is unchanged - as is the case when it has just been loaded or saved in a
file. Add the following data member definition to the class:
private boolean sketchChanged = false; // Model changed flag
This is sometimes referred to as the 'dirty' flag for the model, because it records when something has
been done to sully the pristine state of the model data. The flag is false by default because the sketch
is empty and therefore unchanged by definition. Any change that the user makes to the model should
result in the flag being set to true , and when the model is written to a file, the flag should be reset to
false . This will avoid unnecessary save operations while the sketch in memory remains unchanged.
We already have in place the means to signal changes to a sketch, since the SketchModel class has
Observable as a base class. An Observable object can automatically notify any registered Observer
objects when a change takes place. All we need to do is to make the SketchFrame class implement the
Observer interface, and register the application window as an observer of the sketch object.
public class SketchFrame extends JFrame
implements Constants, ActionListener, Observer {
// Method called by SketchModel object when it changes
public void update(Observable o, Object obj) {
sketchChanged = true;
}
// Rest of the class as before...
}
The Observer interface and the Observable class are defined in the java.util package, so we
must import them into the SketchFrame.java file with the statements:
import java.util.Observer;
import java.util.Observable;
We can register the application window as an observer for the SketchModel object by adding one
statement to the init() method in the Sketcher class:
sketch.addObserver(window); // Register window as observer
The window field in the Sketcher object stores a reference to the application window. Whenever an
element is added to the sketch, or deleted from it, the application window object will be notified. We
can now press ahead with serializing the document.
Search WWH ::




Custom Search