Adding Undo and Redo to a Text Component - Java Swing

Java examples for Swing:JTextComponent

Description

Adding Undo and Redo to a Text Component

Demo Code

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;

public class Main {
  public static void main(String[] argv) {
    JTextComponent textcomp = new JTextArea();
    final UndoManager undo = new UndoManager();
    Document doc = textcomp.getDocument();

    // Listen for undo and redo events
    doc.addUndoableEditListener(new UndoableEditListener() {
      public void undoableEditHappened(UndoableEditEvent evt) {
        undo.addEdit(evt.getEdit());/* w  ww  .ja va  2  s  .co m*/
      }
    });

    textcomp.getActionMap().put("Undo", new AbstractAction("Undo") {
      public void actionPerformed(ActionEvent evt) {
        try {
          if (undo.canUndo()) {
            undo.undo();
          }
        } catch (CannotUndoException e) {
        }
      }
    });

    // Bind the undo action to ctl-Z
    textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
    textcomp.getActionMap().put("Redo", new AbstractAction("Redo") {
      public void actionPerformed(ActionEvent evt) {
        try {
          if (undo.canRedo()) {
            undo.redo();
          }
        } catch (CannotRedoException e) {
        }
      }
    });

    // Bind the redo action to ctl-Y
    textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
  }
}

Related Tutorials