如何将JTextPane中的位置与HTMLDocument转换为JTextPane字符串文本

时间:2015-08-06 09:34:12

标签: java html string swing jtextpane

我在java swing中有一个包含JTextPaneHTMLDocument的应用程序。假设我将窗格的文本设置为:

<html>
   <head>

   </head>
   <body>
       <p style="margin-top: 0">
            I have a problem now.
       </p>
   </body>
</html>

所以我看到文字“我现在有问题”。在窗格上。

我们假设我点击了一个窗格,插入符号设置在“问题”字中的“p”和“r”之间。在这种情境中,如果我在getCaretPosition上调用JTextPane,它将返回10(如果我算得上:) :)。

现在知道这个位置我想把这个位置转换成上面写的html字符串中的位置(如果我算得好的话,这又是94):) 怎么做?

1 个答案:

答案 0 :(得分:1)

首先,你必须明白在html中你不能保持“插入位置”的逻辑。正如斯坦尼斯拉夫告诉你的那样,Hello<html><body>Hello</body></html>之间的<html> <body>Hello</body> </html>也可以翻译,这是没有意义的。在这种情况下,你怎么知道哪个位置对应什么?

错误是尝试将JTextPane文本内容与其HTML转换进行比较。相反,您应该将HTMLDocument与DOM进行比较。所以,首先,你需要一个像JSoup这样的html解析器。

将JSoup添加到项目后,您可以非常轻松地在html和JTextPane内容之间建立并行。

您可以使用此方法获取html:

public static String getHTMLContent(HTMLDocument htmlDoc, int startOffset, int length) {
    StringWriter writer = new StringWriter();
    try {
        new HTMLEditorKit().write(writer, htmlDoc, startOffset, length);
    } catch (IOException | BadLocationException ex) {
        Logger.getLogger(Editeur.class.getName()).log(Level.SEVERE, null, ex);
    }
    String html = writer.toString();
    return html;
}

然后你可以用Jsoup解析它:

Document doc = Jsoup.parse(html);
doc.getElementById("myId");//get the element by its ID

所以,现在,如果你想在生成的html中找到HTMLDocument中的特定元素,你需要做的是用<span>围绕它,你将给出一个ID,然后得到它与getElementById。为此,您可以使用HTMLEditorKit.insertHTML

(new HTMLEditorKit()).insertHTML(htmlDoc, pos, "<span id='myId'>element of interest</span>", 0, 0, Tag.SPAN);

例如,要获取所选文本的位置,您可以执行以下操作:

    if (getSelectedText() != null && getSelectedText().length()>0) {
        try {
            String selectedText = getSelectedText()
            htmlDoc.remove(getSelectionStart(), this.getSelectedText().length());
            (new HTMLEditorKit()).insertHTML(htmlDoc, pos, "<span id='myId'>"+selectedText+"</span>", 0, 0, Tag.SPAN);
        } catch (BadLocationException ex) {
            Logger.getLogger(Editeur.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

现在,您可以轻松地从Jsoup获取您感兴趣的部分或使用getElementById,或者从Java获取HTMLDocument.getElement(id)

如果需要,我可以提供有关具体要点的更多细节。

相关问题