Undo/Redo Commands

GUI Commands provides basic commands for handling undo and redo. The three core classes are:

  1. UndoContext - An extension of Swings UndoManager that provides notifications when the current edit state changes. It can be used as a drop-in replacement for UndoManager.
  2. UndoCommand - Undoes the last edit in the UndoContext.
  3. RedoCommand - Redoes the last edit in the UndoContext.

To use the undo and redo commands you need to:

  1. Bind the undo and redo commands to a CommandContainer.
  2. Set the UndoContext of the container (or on any parent in the hierarchy).
   CommandContainer container = ...;

   // create and bind our commands
   UndoCommand undoCommand = new UndoCommand("undo");
   UndoCommand redo = new UndoCommand("redo");

   undoCommand.bind(container);
   redoCommand.bind(container);

   // configure the undo context.
   UndoContext undoContext = new UndoContext();
   container.setUndoContext(undoContext);

   // use the context
   JTextPane textPane = ...;
   textPane.addUndoableEditListener(undoContext);

You can change the UndoContext at any time. The commands will be notified of the change and update appropriately.