如何从 DocumentListener 中获取添加、删除或更改的字符?
我有 JTextAreas 并需要获取添加、删除或更改的字符。我该怎么做?
I have JTextAreas and need to get chars, which are added, removed or changed to it. How do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
添加很简单,您只需使用 DocumentListener 即可。
要处理添加和删除,您可以使用 DocumentFilter。我相信当您添加/删除文本时会调用 Replace() 方法。
编辑:
DocumentFilter 在删除时不会被调用。因此,了解删除的唯一方法(除了保留重复的文档之外)是创建一个自定义文档并重写remove(...) 方法。然后,您可以在将字符串从文档中删除之前提取该字符串。
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.
您可以获得偏移量和长度(甚至源文档),因此可以从中读取字符。如果您想查看删除的字符是什么,您必须保留文档内容的副本。
Swing 文档应该是线程安全的(呵呵)。但是,如果其他线程中发生多个更改(事件总是在 EDT 上触发,只是为了让事情变得更有趣),那么角色数据可能不是最新的。对此你无能为力。即使其他事件侦听器也可能最终间接更改文档内容。
一般来说,处理事件的简单方法是完全忽略事件对象。您需要知道的只是您正在收听的对象中(可能已经)发生了一些变化。这将为您提供健壮且更易于理解的代码。如果您确实需要进行更改,camickr 提到的
DocumentFilter
是自 swingall.jar 以来添加到 Swing 中的有用的东西(除了更好的原生 L&F 保真度)。(请注意,许多人无法阅读 DocumentListener.changedUpdate - 它适用于属性更改,而不是字符。)
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.)