Undo functionality in JTextArea

后端 未结 2 1511
离开以前
离开以前 2021-01-12 17:52

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

相关标签:
2条回答
  • 2021-01-12 18:27

    I'm not sure but maybe you can not addKeyListener for your gui.
    For example;

    class Example implements KeyListener{
    
      .
      .
      .
    
      this.addKeyListener(this); // if want to add key listener for main container
    
      .
      .
      .
    
    }
    

    this is about how to use key listener.

    0 讨论(0)
  • 2021-01-12 18:30

    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();
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题