Java Reference
In-Depth Information
And that's it! The last two classes make the
UndoDrawing
example class (Listing 21-4) work.
When creating your own undoable classes, you will need to subclass a nonundoable class and
then add the necessary support to make it undoable. In addition, you will need to define an
UndoableEdit
implementation to support your specific class.
Using an Outside Object to Manage Undo States
In the previous example, it was the responsibility of your custom
UndoableEdit
implementation
to maintain the before-and-after state of the undoable object. The Swing Undo Framework
also supports the ability of an object outside the undoable edit implementation to manage the
state. When using an outside object for state management, it isn't necessary to implement the
UndoableEdit
interface yourself. Instead, you can use the
StateEdit
class as the
UndoableEdit
implementation. The
StateEdit
class then relies on a class to implement the
StateEditable
interface to manage the before-and-after storage of the state of an undoable object (within a
Hashtable
).
StateEditable Interface
The
StateEditable
interface consists of two methods and a meaningless string constant.
public interface StateEditable {
public final static String RCSID;
public void restoreState(Hashtable state);
public void storeState(Hashtable state);
}
An object that supports the undoing of its operations stores its state with the
storeState(
➥
Hashtable)
method. This is all the information about the state of the object that can change.
Then restoring the state of the object is done in the
restoreState(Hashtable)
method.
To demonstrate, let's see how to rewrite the
UndoableDrawingPanel
example. Using this
interface with the updated, undoable drawing panel involves implementing the interface, and
storing and getting the polygon shown earlier in Figure 21-5. That's because the polygon is the
only state information we care about undoing. The source code is shown in Listing 21-7.
Listing 21-7.
The StateEditable Implementation of the Updated Component
public class UndoableDrawingPanel2 extends JPanel implements StateEditable {
private static String POLYGON_KEY = "Polygon";
public void storeState(Hashtable state) {
state.put(POLYGON_KEY, getPolygon());
}