我正在尝试在JTextArea中实现撤消功能。用Google搜索教程,并按照其中一个教程编写了以下代码。按下Ctrl + Z键会触发事件。它对我不起作用。我想念什么吗?

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());
        }
    });
}

最佳答案

从您的榜样来看,很难知道您做了多少,但是我能够做到这一点...

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();
        }
    }
});

10-08 00:51