-
-
Save yashrs/e4e064f036157dbbb0675bee6d88caee to your computer and use it in GitHub Desktop.
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
public void addUndoRedoCapabilities(JTextArea textcomp){ | |
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()); | |
} | |
}); | |
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"); | |
// Create a redo action and add it to the text component | |
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"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment