Using undo and redo for JTextArea

后端 未结 5 973
一向
一向 2021-01-04 12:33

I am making a text editor using Java swing. I am using JTextArea for the same. I want to know how I can use Undo and Redo functionality in JTextArea as I am not able to use

5条回答
  •  独厮守ぢ
    2021-01-04 12:38

    You can do like this

    UndoManager manager = new UndoManager();
    textArea.getDocument().addUndoableEditListener(manager);
    

    Once the manager is attached to the document of the JTextArea, it will monitor all changes to the contents of the text area.

    After attaching the manager to the text component, you must provide some means to tell the manager to undo/redo an operation.

    Call the public void undo() and public void redo() method of the UndoManager where necessary(Eg. actionPerformed() method of an actionlistener)

    You can attach Action objects to a button in the following way instead of calling undo() and redo() methods which simplifies the task:

    JButton undoButton = new JButton(UndoManagerHelper.getUndoAction(manager));
    JButton redoButton = new JButton(UndoManagerHelper.getRedoAction(manager));
    

提交回复
热议问题