JEditorPane, HTMLEditorKit - custom action inserting custom tag

一世执手 提交于 2019-12-05 14:39:08

I've found a workaround. The tag is inserted this way:

ModifiedHTMLDocument doc = (ModifiedHTMLDocument) editor.getDocument();
int offset = editor.getSelectionStart();
//insert our special tag (if the tag is not bounded with non-whitespace character, nothing happens)
doc.insertHTML(offset, "-<specialTag />-");
//remove leading and trailing minuses
doc.remove(offset, 1); //at the current position is the minus before tag inserted
doc.remove(offset + 1, 1); //the next sign is minus after new tag (the tag is nowhere)
//Note: no, you really cannot do that: doc.remove(offset, 2), because then the tag is deleted

My ModifiedHTMLDocument contains a method insertHTML(), which calls the medhod hidden by reflection:

public void insertHTML(int offset, String htmlText) throws BadLocationException, IOException {
    if (getParser() == null)
        throw new IllegalStateException("No HTMLEditorKit.Parser");

    Element elem = getCurrentElement(offset);

    //the method insertHTML is not visible
    try {
        Method insertHTML = javax.swing.text.html.HTMLDocument.class.getDeclaredMethod("insertHTML",
                new Class[] {Element.class, int.class, String.class, boolean.class});
        insertHTML.setAccessible(true);
        insertHTML.invoke(this, new Object[] {elem, offset, htmlText, false});
    }
    catch (Exception e) {
        throw new IOException("The method insertHTML() could not be invoked", e);
    }
}

The last piece of our brick-box is a method looking for the current element:

public Element getCurrentElement(int offset) {
    ElementIterator ei = new ElementIterator(this);
    Element elem, currentElem = null;
    int elemLength = Integer.MAX_VALUE;

    while ((elem = ei.next()) != null) { //looking for closest element
        int start = elem.getStartOffset(), end = elem.getEndOffset(), len = end - start;
        if (elem.isLeaf() || elem.getName().equals("html"))
            continue;
        if (start <= offset && offset < end && len <= elemLength) {
            currentElem = elem;
            elemLength = len;
        }
    }

    return currentElem;
}

This method is also a member of the ModifiedHTMLDocument class.

The solution is not pure, but it solves provisionally the problem. I hope I'll find a better kit. I'm thinking about JWebEngine. That should be replacement for current poor HTMLEditorKit, but I don't know, whether it allows me to add my custom tags.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!