views:

103

answers:

2

Hi,

I have JTextAreas and need to get chars, which are added, removed or changed to it. How do I do this?

+1  A: 

Add is easy, you just use a DocumentListener.

To handle add and remove you might be able to use a DocumentFilter. I believe the replace() method is invoked when you both add/remove text.

Edit:

The DocumentFilter does NOT get invoked on a remove. So the only way to know about a remove (other than keeping a duplicate Document) is to create a custom Document and override the remove(...) method. Then you can extract the String before it is removed from the Document.

camickr
DF.replace() with empty string is called if I remember correctly
Rastislav Komara
A: 

You can get the offset and length (and even the source Document), so the characters can be read from that. If you wanted to see what the removed characters were, you'd have to have kept a copy of the document contents.

Swing documents are supposed to be thread-safe (hehe). But if multiple changes happen in other threads (events are always fired on the EDT just to make things more fun), then the character data might not be up to date. There isn't really much you can do about this. Even other event listeners could end up indirectly altering the document contents.

Generally, the easy approach in with events is to ignore the event object altogether. All you need to know is something (may have) changed in the objects you are listening to. This should give you robust and easier to understand code. If you really need to work on the changes, DocumentFilter mentioned by camickr is the useful thing added to Swing since swingall.jar (other than better native L&F fidelity).

(Note, many people fail to read the docs for DocumentListener.changedUpdate - it applies to attributes changing, not characters.)

Tom Hawtin - tackline