[英]Get changed content in DocumentEvent
The goal: 目标:
Working with a JEditorPane and HTMLDocuments I need to react to the removal of images, ie Elements defined by <img>..</img>
tags. 使用JEditorPane和HTMLDocuments,我需要对图像的删除做出反应,即<img>..</img>
标记定义的Elements。
What I tried: 我试过的
For now I use DocumentListeners to react to DocumentEvents which are fired upon changes to a document. 现在,我使用DocumentListeners来响应DocumentEvents,这些事件在文档更改时触发。 Unfortunately, DocumentEvents do not directly contain information about the changed content, so I can't identify what kind of element has been removed. 不幸的是,DocumentEvents不直接包含有关更改内容的信息,因此我无法确定已删除了哪种元素。 It seems all I can do is iterate over all Elements of the document and call the events getChange(Element). 看来我能做的就是遍历文档的所有元素并调用事件getChange(Element)。
document.addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent arg0) {
ElementIterator iter = new ElementIterator(document);
Element element;
while ((element=iter.next()) != null) {
ElementChange change = arg0.getChange(element);
if (change != null) {
Element[] children = change.getChildrenRemoved();
for (Element child : children) {
Object name = child.getAttributes().getAttribute(StyleConstants.NameAttribute);
System.out.println((HTML.Tag)name);
}
}
}
notifyContentChanged();
}
});
}
Although this solution works partially (sometimes when deleting an image the sysout reports a p-implied
instead of a img
) I would really appreciate other solutions. 尽管此解决方案部分有效(有时在删除映像时sysout报告为p-implied
而不是img
),但我还是很感激其他解决方案。 Probably, someone knows a simple way of getting the String
associated with a change in the document? 也许有人知道获取与文档更改相关的String
的简单方法?
SOLUTION 解
In accordance to the accepted answer, the following code demonstrates the use of DocumentFilters as Listeners (for image removal in this case). 根据接受的答案,以下代码演示了将DocumentFilters用作侦听器(在这种情况下为图像删除)。
document.setDocumentFilter(new DocumentFilter() {
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
if (document.getCharacterElement(offset).getName().equals(HTML.Tag.IMG.toString())) {
.
.
}
super.remove(fb, offset, length);
}
});
DocumentEvent has getOffset() and getLength() methods. DocumentEvent具有getOffset()和getLength()方法。 Normally images are leaves so you can use htmlDocument.getCharacterElement() from the range of change and check whether they are images. 通常,图像是叶子,因此您可以在更改范围内使用htmlDocument.getCharacterElement()并检查它们是否为图像。
UPDATE: as result of discusing in commetns 更新:由于逗号引起的
You can add a DocumentFilter overriding remove() and use it as listener to get deleted fragment (in fact fragment to-be-deleted). 您可以添加一个重写remove()的DocumentFilter并将其用作侦听器,以获取已删除的片段(实际上是要删除的片段)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.