Java JTextComponent Action setHistoryActions(JTextComponent textComponent)

Here you can find the source of setHistoryActions(JTextComponent textComponent)

Description

set History Actions

License

Open Source License

Declaration

private static void setHistoryActions(JTextComponent textComponent) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;

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 {
    private static void setHistoryActions(JTextComponent textComponent) {
        Document doc = textComponent.getDocument();
        UndoManager undo = new UndoManager();
        doc.addUndoableEditListener(new UndoableEditListener() {
            @Override//from  w  ww  . ja va 2s .  c  o  m
            public void undoableEditHappened(UndoableEditEvent evt) {
                undo.addEdit(evt.getEdit());
            }
        });

        textComponent.getActionMap().put("Undo", new AbstractAction("Undo") {
            private static final long serialVersionUID = 2048749213313143683L;

            @Override
            public void actionPerformed(ActionEvent evt) {
                try {
                    if (undo.canUndo()) {
                        undo.undo();
                    }
                } catch (CannotUndoException e) {
                }
            }
        });
        textComponent.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");

        textComponent.getActionMap().put("Redo", new AbstractAction("Redo") {
            private static final long serialVersionUID = 2048749213313143683L;

            @Override
            public void actionPerformed(ActionEvent evt) {
                try {
                    if (undo.canRedo()) {
                        undo.redo();
                    }
                } catch (CannotRedoException e) {
                }
            }
        });
        textComponent.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
    }
}

Related

  1. getAction(JTextComponent component, String actionName)
  2. getAction(JTextComponent target, Class aClass)