Java Reference
In-Depth Information
The UndoManager manages the edit operations on an editable object by serving as an
UndoableEditListener and responding to the creation of each UndoableEditEvent . When
an UndoableEdit can't be undone, a CannotUndoException is thrown. In addition, when an
UndoableEdit can't be redone, a CannotRedoException is thrown.
If you want to create objects that support undoable and redoable operations, the objects
need to implement the StateEditable interface, and they can use the UndoableEditSupport
class to help manage the list of UndoableEdit objects.
Before going into the details of the individual pieces of the Undo Framework, let's explore
how to use it with the Swing text components. If this is all you want to do, you don't need to
understand how the rest works.
Using the Undo Framework with Swing Text
Components
The Swing text components already support the necessary undo and redo capabilities. You
merely need to manage them with an UndoManager and tell the manager when to undo/redo
something.
As an example, consider a program that includes a JTextArea with two toolbar buttons for
undoing and redoing a text operation, as shown in Figure 21-1.
Figure 21-1. Undo Swing text component usage example
To enable the JTextArea shown in Figure 21-1 to support undoable operations, you must
attach an UndoableEditListener to the Document of the component. Using an UndoManager as
the listener is all you need to do. First, you create the manager, and then you attach it.
UndoManager manager = new UndoManager();
textArea.getDocument().addUndoableEditListener(manager);
Once the manager is attached to the document of the JTextArea , it will monitor all changes
to the contents of the text area. Because each of the Swing text components has a Document data
model, you can associate an UndoManager with each of these components directly.
After attaching the manager to the text component, you must provide some means to tell
the manager to undo/redo an operation. Normally this would be done through a menu selec-
tion or a toolbar button selection. In Figure 21-1, this is done with the help of buttons on a
JToolBar , with one button for each command. For the Undo button, you want the manager to
undo an operation. Therefore, the ActionListener for the button should call the public void
undo() method of the UndoManager . The Redo button's ActionListener should call the manager's
 
Search WWH ::




Custom Search