How do I let my Swing text component support undo/redo?

John Zukowski

The Swing text components come with built in support for undoing and redoing text operations. All you have to do is associate an UndoManager to the Document of the text component:

JTextField textField = new JTextField();
UndoManager manager = new UndoManager();
Document document = textField.getDocument();

Then, when it comes time to undo or redo the last edit, you would notify the UndoManager by calling either the undo() or redo() method of the manager. If the manager cannot undo an operation, the runtime exception CannotUndoException is thrown. If a redo operation cannot be redone, the runtime exception CannotRedoException is thrown.