Getting the removed text from a Java text component
-
09-09-2019 - |
Question
A JTextComponent
allows you to add a DocumentListener
to its Document
, which will tell you when text was added or removed, and the offset and length of the change. It will not, however, tell you what the text of the change was.
This is not much of a problem for text addition, as you can use the offset and the length to find the added text. However, you can't use it to find the deleted text, as the text is already gone.
Has anyone run into this problem before? How can you get the string that was deleted from a document?
Solution
Install a DocumentFilter
into the AbstractDocument
.
(BTW: In Swing it's usually best to go straight to the model (in this case document).)
OTHER TIPS
Every time text is added, store the document in memory. Every time text is removed, compare the document to what was last stored to determine what was removed.
store the original version of the text in a property where you can still do the "offset-length-trick" to get the removed string. should do fine