Java Reference
In-Depth Information
public void restoreState(Hashtable state) {
Polygon polygon = (Polygon)state.get(POLYGON_KEY);
if (polygon != null) {
setPolygon(polygon);
}
}
}
The
Hashtable
that the
restoreState()
method returns contains only key/value pairs that
changed. It's possible that the
get()
method of the
Hashtable
returns
null
for something that
you explicitly
put()
in the hash table. Therefore, as shown in Listing 21-7, you're required to
add an
if-null
check after getting any state information from the hash table.
StateEdit Class
After you've implemented the
StateEditable
interface, you can use the
StateEdit
class as the
UndoableEdit
implementation. Where the previous
UndoableDrawingPanel
example created a
custom
UndoableDrawEdit
, the new class creates a
StateEdit
instance.
The
StateEdit
constructor accepts a
StateEditable
object that you're going to change and
an optional presentation name. After creating the
StateEdit
object, modify the
StateEditable
object and then tell the
StateEdit
to
end()
the modifications to the
StateEditable
object.
When the
StateEdit
object is told that the modifications have ended, it compares the before-
and-after states of the state editable object and removes any key/value pairs that didn't change
from the hash table. You can then post the
UndoableEdit
to the list of
UndoableEditListener
objects through the list maintained by the
UndoableEditSupport
class.
StateEdit stateEdit = new StateEdit(UndoableDrawingPanel2.this);
// Change state of UndoableDrawingPanel2
polygon.addPoint(mouseEvent.getX(), mouseEvent.getY());
// Done changing state
stateEdit.end();
undoableEditSupport.postEdit(stateEdit);
After the edit is posted, the
UndoManager
manages the
StateEdit
instance of
UndoableEdit
,
just like any other undoable edit object. The
UndoManager
can then request the
StateEdit
object
to tell its
StateEditable
object to restore its previous state. This holds for any other
UndoableEdit
object. Therefore, no other source code needs to change.
A Complete StateEditable/StateEdit Example
The reworking of the
UndoableDrawingPanel
example is presented in Listing 21-8, with the
differences from Listing 21-5 shown in boldface. This version uses the
StateEditable
/
StateEdit
combination just described. The earlier test program is included as the
main()
method to keep the complete example together. With the exception of the class name change
for the drawing panel, the test program didn't change and will still result in what you see in
Figure 21-5, assuming the same set of points in the polygon.