Last active
March 10, 2019 12:21
-
-
Save ezhov-da/54597b7e2e5a4ac229e503b39e8232f2 to your computer and use it in GitHub Desktop.
java undo redo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.event.ActionEvent; | |
import java.util.logging.Logger; | |
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; | |
/** | |
* Установка отмены и повтора ввода текста для текстовых компонентов | |
* <p> | |
* @author ezhov_da | |
*/ | |
public class UndoRedoManager | |
{ | |
private static final Logger LOG = Logger.getLogger(UndoRedoManager.class.getName()); | |
public synchronized static void setUR(JTextComponent textComponent) | |
{ | |
final UndoManager undo = new UndoManager(); | |
Document doc = textComponent.getDocument(); | |
doc.addUndoableEditListener(new UndoableEditListener() | |
{ | |
public void undoableEditHappened(UndoableEditEvent evt) | |
{ | |
undo.addEdit(evt.getEdit()); | |
} | |
}); | |
textComponent.getActionMap().put("Undo", | |
new AbstractAction("Undo") | |
{ | |
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") | |
{ | |
public void actionPerformed(ActionEvent evt) | |
{ | |
try | |
{ | |
if (undo.canRedo()) | |
{ | |
undo.redo(); | |
} | |
} catch (CannotRedoException e) | |
{ | |
} | |
} | |
}); | |
textComponent.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment