撤消JTextArea中的功能

时间:2012-08-19 23:35:31

标签: java swing

我正在尝试在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());
        }
    });
}

2 个答案:

答案 0 :(得分:16)

从你的例子来看,很难知道你做了多少,但我能够让它发挥作用......

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

答案 1 :(得分:0)

我不确定,但也许你不能为你的gui添加KeyListener。
例如;

class Example implements KeyListener{

  .
  .
  .

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

  .
  .
  .

}

this是关于如何使用密钥监听器。