I am trying to implement undo functionality in JTextArea
. Googled for tutorial and followed one of the tutorial and wrote the below code. The event is triggered when Ctrl+Z key is pressed. Its not working for me. Am I missing something?
private void undoActionPerformed(java.awt.event.ActionEvent evt) {
Document doc = editorTextArea.getDocument();
final UndoManager undo = new UndoManager();
doc.addUndoableEditListener(new UndoableEditListener() {
@Override
public void undoableEditHappened(UndoableEditEvent e) {
undo.addEdit(e.getEdit());
}
});
}
You can use JTextArea#setLineWrap(true) by default is set to false. Sets the line-wrapping policy of the text area. If set to true the lines will be wrapped if they are too long to fit within the allocated width. If set to false, the lines will always be unwrapped.
selectAll(); JTextArea0. replaceSelection(""); This selects the entire textArea and then replaces it will a null string, effectively clearing the JTextArea.
The JTextArea class provides a component that displays multiple lines of text and optionally allows the user to edit the text. If you need to obtain only one line of input from the user, you should use a text field.
From you're example, it's difficult to know how much you've done, but I was able to get this to work...
private UndoManager undoManager;
// In the constructor
undoManager = new UndoManager();
Document doc = textArea.getDocument();
doc.addUndoableEditListener(new UndoableEditListener() {
@Override
public void undoableEditHappened(UndoableEditEvent e) {
System.out.println("Add edit");
undoManager.addEdit(e.getEdit());
}
});
InputMap im = textArea.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap am = textArea.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "Undo");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "Redo");
am.put("Undo", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if (undoManager.canUndo()) {
undoManager.undo();
}
} catch (CannotUndoException exp) {
exp.printStackTrace();
}
}
});
am.put("Redo", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if (undoManager.canRedo()) {
undoManager.redo();
}
} catch (CannotUndoException exp) {
exp.printStackTrace();
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With