How do I get added, removed, or changed characters from the DocumentListener?

I have a JTextAreas and need to get characters that are added, removed, or changed to it. How to do it?

+2


source to share


2 answers


It's easy to add, you just use a DocumentListener.

You can use DocumentFilter to handle adding and removing. I believe the replace () method is called when you add / remove text.



Edit:

DocumentFilter is NOT triggered on delete. So the only way to know about deletion (other than keeping the duplicate document) is to create a custom document and override the remove (...) method. You can then extract the line before removing it from the document.

+1


source


You can get the offset and length (and even the source Document

) so that characters can be read from that. If you wanted to see what the deleted characters were, you would need to keep a copy of the content of the document.

Swing documents must be thread safe (hehe). But if multiple changes occur on other threads (events are always triggered by EDT to make them more fun), then the symbol data may not be updated. In fact, you cannot do this. Even other event listeners can indirectly change the content of the document.



Generally, a simple approach to events is to ignore the event object altogether. All you need to know is that something has (possibly) changed in the objects you are listening to. This should give you reliable and readable code. If you really need to work on changes, the DocumentFilter

one mentioned by camickr is a useful thing added to Swing with swingall.jar (other than the best original L&F fidelity).

(Note: a lot of people don't read the docs for DocumentListener.changedUpdate - this refers to attribute changes, not symbols.)

0


source







All Articles