我有一个可编辑的JTextpane,并且想要启用HTML,以便初始文本显示为格式化的。但是,此操作有效,现在字符串中的第一个字符为'\ n',这意味着字符串比预期的长度长1个字符。我可以删除它(例如,对于“ foo”一词,我可以按4次退格键先删除该词,然后再删除“ \ n”)。

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

这是我的示例代码:

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);
        }
    }
}

10-07 19:10
查看更多