Java Reference
In-Depth Information
The minimum methods to override are undo() and redo() , although you'll probably also choose
to override getPresentationName() to give a better name to the undoable operation.
Because the Command design pattern has the Concrete Command (that is, the
UndoableEdit implementation) invoke the operation, the constructor must save any informa-
tion necessary to make the operation undoable. In the case of the drawing panel, you need to
save a reference to the panel and its current polygon. Then when the operation is asked to
undo itself, the original polygon can be restored. To support redoing the undo operation, the
undo() method must also save the new polygon; otherwise, the redo() operation wouldn't
know how to change things back. It may sound like quite a bit of work, but it really isn't. The
complete class definition for the UndoableEdit implementation follows in Listing 21-6.
Listing 21-6. The UndoableDrawEdit Undoable Command
import javax.swing.undo.*;
import java.awt.*;
public class UndoableDrawEdit extends AbstractUndoableEdit {
UndoableDrawingPanel panel;
Polygon polygon, savedPolygon;
public UndoableDrawEdit(UndoableDrawingPanel panel) {
this.panel = panel;
polygon = panel.getPolygon();
}
public String getPresentationName() {
return "Polygon of size " + polygon.npoints;
}
public void redo() throws CannotRedoException {
super.redo();
if (savedPolygon == null) {
// Should never get here, as super() doesn't permit redoing
throw new CannotRedoException();
} else {
panel.setPolygon(savedPolygon);
savedPolygon = null;
}
}
public void undo() throws CannotUndoException {
super.undo();
savedPolygon = panel.getPolygon();
panel.setPolygon(polygon);
}
}
Search WWH ::




Custom Search