创建 text/html JTextPane 时的换行符



我有一个可编辑的JTextpane,并希望启用HTML,以便初始文本显示为格式化。但是,这有效,现在字符串中的第一个字符是"",这意味着字符串比预期长 1 个字符。我可以删除它(例如,对于单词"foo",我可以按退格键 4 次先删除单词,然后再删除"")。

显然,如果我只立即拥有所需的字符串,而没有任何技巧可以删除它,我会更喜欢它。我将不胜感激对此的任何帮助!

这是我的示例代码:

JTextPane testPane = new JTextPane();
testPane.setContentType("text/html");
testPane.setText("<html><body><span style='color:red'>My Text which will have a newline at the beginning.</span></body></html>");
// testPane.setText("the same newline at the start even without the HTML tags");
StyledDocument doc = testPane.getStyledDocument();
SimpleAttributeSet myAttributeSet = new SimpleAttributeSet();
StyleConstants.setFontSize(myAttributeSet, 14);
StyleConstants.setFontFamily(myAttributeSet, Font.DIALOG);
doc.setParagraphAttributes(0, doc.getLength(), myAttributeSet, false);
testPane.setDocument(doc);
myGridPanel.add(testPane, gbc);

请注意,无论我是否拥有所有这些标签信息(即"),都会显示换行符字符。

我将不胜感激任何关于我做错了什么或我应该做些什么来避免这个额外的字符的提示。

提前感谢!

您看到的n是文档中为头部保留的位置。小心,这也意味着身体从字符 1 开始。您之前编写的所有内容都不会显示。

如果你不需要它,你可以做:

public static void removeHead(JTextPane testPane) {
    javax.swing.text.Element head = testPane.getDocument().getDefaultRootElement().getElement(0);
    if(head.getName().equals("head")) {
        try {
            testPane.getDocument().remove(0, head.getEndOffset());
        } catch (BadLocationException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

最新更新