Java Reference
In-Depth Information
private boolean sketchChanged = false;
// Model changed flag
Directory "Sketcher 1 saving a sketch to a file"
This sort of variable is sometimes referred to as a “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 whenever the model is written to a file, the flag should be re-
set to
false
. By checking the state of this flag you can avoid unnecessary Save operations while the sketch
in memory remains unchanged.
You already have in place the means to signal changes to a sketch because the
SketcherModel
class has
Observable
as a base class. As you know, an
Observable
object can automatically notify any registered
Observer
objects when a change takes place. All you need to do is to make the
SketcherFrame
class im-
plement the
Observer
interface and register the application window as an observer of the sketch object:
public class SketcherFrame extends JFrame implements ActionListener, Observer {
// Constructor and other methods as before...
// Method called by SketcherModel object when it changes
public void update(Observable o, Object obj) {
sketchChanged = true;
}
// Rest of the class as before...
}
Directory "Sketcher 1 saving a sketch to a file"
The
update()
member of
SketcherFrame
will be called by the
sketch
object whenever the sketch
changes in some way. You record the change by setting
sketchChanged
to
true
. This implies that the sketch
in its current state has not been saved, and when the sketch is saved, you must set
sketchChanged
back to
false
.
The
Observer
interface and the
Observable
class are defined in the
java.util
package, so you must
import the class names into the
SketcherFrame.java
file with the following statement:
import java.util.*;
You can register the application window as an observer for the
SketcherModel
object by adding one
statement to the
createGUI()
method in the
Sketcher
class:
private void creatGUI() {
// Code as before...
sketch = new SketcherModel(); // Create the model