Using undo and redo for JTextArea

As I understand it, JTextArea has no inherent Undo/Redo functionality built in, but a Google search did find this article which might be helpful.

There apparently exists an Undo Manager in javax.swing which you can hook up to the JTextArea's change events.


You can do like this

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.

After attaching the manager to the text component, you must provide some means to tell the manager to undo/redo an operation.

Call the public void undo() and public void redo() method of the UndoManager where necessary(Eg. actionPerformed() method of an actionlistener)

You can attach Action objects to a button in the following way instead of calling undo() and redo() methods which simplifies the task:

JButton undoButton = new JButton(UndoManagerHelper.getUndoAction(manager));
JButton redoButton = new JButton(UndoManagerHelper.getRedoAction(manager));

Tags:

Java

Swing