Compound Undo Manager
Posted by Rob Camick on October 27, 2008
Swing text components support undo/redo of text entered in a Document. Every time a change is made to the Document an UndoableEditEvent is generated. The UndoManager keeps track of these events and allows you to invoke undo/redo on them. The default implemetation of the UndoManager is to undo/redo individual events. This means each character you type is undone/redone separately. I don’t know about you, but I would rather undo/redo releated events together at the same time.
The first thing we need to do is to define what related events are. Characters typed sequentially into a Document or removed sequentially from a Document should be related. That is, if you type a few characters, use the backspace key to correct a typo and then continue typing, the events should be related. Also, any attribute changes created as a result of the characters entered should be related. This would happen, for example, when doing syntax highlighting as text is typed. However, if you manually position the caret at a different location in the Document and then start typing, you would start a new series of related events.
A class called CompoundEdit already exists and allows us to combine individual edits events into one. All we need to do is customize the UndoManger and implements the rules for combining these individual edits. The CompoundUndoManager class tries to implement these rules the best it can. Undo/redo support is then added to a text component with the following line of code:
CompoundUndoManager um = new CompoundUndoManager(textComponent);
You can then create menu items or buttons to invoke the undo/redo functionality of the UndoManager using the Actions provided:
JButton undo = new JButton(um.getUndoAction());
JButton redo = new JButton(um.getRedoAction());
Add the text component and the buttons to your GUI and you are ready to go.
As you can see from the above image, the Webstart demo will show how undo/redo is handled when using syntax highlighting and other attribute changes like bold, italics and underlining.