目標:
JEditorPane と HTMLDocuments を操作する 画像、つまり<img>..</img>
タグで定義された要素の削除に対応する必要があります。
私が試したこと:
今のところ、DocumentListenersを使用して、ドキュメントへの変更時に発生するDocumentEventsに反応します。残念ながら、DocumentEvents には変更されたコンテンツに関する情報が直接含まれていないため、削除された要素の種類を特定できません。私ができることは、ドキュメントのすべての要素を反復処理し、イベント 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();
}
});
}
この解決策は部分的に機能しますが (イメージを削除すると、sysout が ap-implied
ではなくa を報告することがありますimg
)、他の解決策を本当に感謝します。おそらく、String
ドキュメントの変更に関連付けられた を取得する簡単な方法を誰かが知っているでしょうか?
解決策
受け入れられた回答に従って、次のコードは 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);
}
});