Antonio Ferreras
Antonio Ferreras

Reputation: 89

JTextPane and undo manager style change

My situation: I have a JTextPane with its own syntax highlighting. I have it set so that when the user stops typing, it updates the style in the text using the setCharacterAttributes() method.

My Issue: When these updates to the style are not performed, the undo manager works as expected. But when I do use it, the undo manager counts those style changes as actual undo-able actions! Meaning hitting Ctrl+z (I have it bound to undo when pressed) it just un-colors the last character i typed. Rather than actually removing/undoing it.

How would I get it so undo-ing and redo-ing only affects text changes and not style/font changes in my StyledDocument?

Thank you.

Upvotes: 2

Views: 357

Answers (2)

Antonio Flaccomio
Antonio Flaccomio

Reputation: 1

After a lot of unsuccessful attempts I figured out a solution. Basically I use a javax.swing.text.PlainDocument.PlainDocument(), call it "undoDoc", together with the standard javax.swing.text.StyledDocument, call it "editDoc"; keep their textual content aligned and connect the UndoManager with the undoDoc; on any unodo/redo operation I copy the entire text from undoDoc to editDoc any analize again the text for syntax highlighting. You find the full code here: https://github.com/usnasoft/usnalib2/blob/main/src/main/java/it/usna/swing/SyntaxEditor.java An usage example is here: https://github.com/usnasoft/usnalib2/blob/main/src/main/java/it/usna/examples/SyntacticTextEditor.java

Upvotes: 0

sorifiend
sorifiend

Reputation: 6307

It sounds like you need to make use of addEdit or the Significant attribute as explained by the UndoManager:

The UndoManager makes use of isSignificant to determine how many edits should be undone or redone. The UndoManager will undo or redo all insignificant edits (isSignificant returns false) between the current edit and the last or next significant edit. addEdit and replaceEdit can be used to treat multiple edits as a single edit, returning false from isSignificant allows for treating can be used to have many smaller edits undone or redone at once. Similar functionality can also be done using the addEdit method.

Sources: https://docs.oracle.com/javase/8/docs/api/javax/swing/undo/UndoableEdit.html

Upvotes: 1

Related Questions