Java tutorial
//package com.java2s; /* * Copyright 2014 kohii. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.InputMap; 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.UndoManager; public class Main { public static void installUndoManager(JTextComponent textComponent) { installUndoManager(textComponent, new UndoManager()); } @SuppressWarnings("serial") public static void installUndoManager(JTextComponent textComponent, final UndoManager undoManager) { Document doc = textComponent.getDocument(); doc.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { undoManager.addEdit(e.getEdit()); } }); ActionMap am = textComponent.getActionMap(); InputMap im = textComponent.getInputMap(); am.put("undo", new AbstractAction("undo") { @Override public void actionPerformed(ActionEvent e) { undoManager.undo(); } @Override public boolean isEnabled() { return undoManager.canUndo(); } }); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, getMenuShortcutKeyMask()), "undo"); am.put("redo", new AbstractAction("redo") { @Override public void actionPerformed(ActionEvent e) { undoManager.redo(); } @Override public boolean isEnabled() { return undoManager.canRedo(); } }); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Y, getMenuShortcutKeyMask()), "redo"); } public static int getMenuShortcutKeyMask() { return Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); } }