Extending UndoManager
Now that we’ve looked at all of the classes and interfaces in the undo framework, we’ll look at a few ideas for extending the functionality it provides.
In this example, we’ll extend UndoManager
to add a few extra features. The
first thing we’ll add is the ability to get a list of the edits stored
in the manager. This is a simple task of returning the contents of the
edits
vector inherited from CompoundEdit
. We also provide access to an
array of significant undoable edits and an array of significant redoable
edits. These might be useful in a game like chess, in which we want to
provide a list of past moves.
The next major feature we add is support for listeners. At this
writing, the current UndoManager
does
not have any way of notifying you when it receives edits. As we saw in
an earlier example, this means that you have to listen to each
edit-generating component if you want to update the user interface to
reflect new undoable or redoable edits as they occur. In our manager, we
simply add the ability to add and remove undoable edit listeners to the
undo manager itself. Each time an edit is added, the undo manager fires
an UndoableEditEvent
to any
registered listeners. This way, we can just add the undo manager as a
listener to each edit-generating component and then add a single
listener to the undo manager to update the UI.
The methods of our new undo manager can be divided into two groups, each supporting one of the two features we’re adding. We’ll split the ...
Get Java Swing, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.