2

I used the UndoManager to add undo and redo functionality to my JTextPane. However, it saves the text every time text is entered, so it undos to the last letter. How can I make it undo to the last word?

Community
  • 1
  • 1
Jutanium
  • 421
  • 3
  • 16

2 Answers2

3

http://java-sl.com/tip_merge_undo_edits.html That's an example of such merging edits.

StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • Thanks! Your website is great, by the way. – Jutanium Aug 06 '12 at 15:30
  • One problem... when the user highlights something and deletes, this happens: `javax.swing.text.BadLocationException: Invalid location at javax.swing.text.GapContent.getChars(GapContent.java:172) at javax.swing.text.GapContent.getString(GapContent.java:150) at javax.swing.text.AbstractDocument.getText(AbstractDocument.java:757) at UndoManager.undoableEditHappened(UndoManager.java:24)` and so on. – Jutanium Aug 08 '12 at 15:25
  • And it only happens when the user highlights and deletes something near the beginning or the end of the text. – Jutanium Aug 08 '12 at 15:44
1

Use UndoableEdit#addEdit(). If you make non-whitespace edits stick together on the undo stack (by absorbing each other through this method) and whitespace edits too, then the next undo will act on the last work or last whitespace gap, which is what you want.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
radai
  • 23,949
  • 10
  • 71
  • 115