Cancel functionality in JTextArea

I am trying to implement undo functions in JTextArea. Googled for the tutorial and followed one of the lessons and wrote the code below. The event fires when you press Ctrl + Z. This does not work for me. Did I miss 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());
        }
    });
}
+5
source share
2 answers

From your example, it's hard to see how much you did, 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();
        }
    }
});
+16
source

I'm not sure, but maybe you cannot add a KeyListener for your gui.
For instance:

class Example implements KeyListener{

  .
  .
  .

  this.addKeyListener(this); // if want to add key listener for main container

  .
  .
  .

}

it's about how to use a key listener.

0
source

All Articles