Markstar
Markstar

Reputation: 873

Newline char when creating text/html JTextPane

I have an editable JTextpane and want to enable HTML so the initial text appears formatted. This works, however, now the first char in the string is '\n', meaning the string is 1 char longer than expected. I can delete this (e.g. for the word 'foo', I can press backspace 4 times to delete the word first and then the '\n').

Obviously, I would prefer it if I only have the desired string right away, without any tricks to delete it afterwards. I would appreciate any help on this!

Here is my example code:

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

Note that the newline char appears whether or not I have all this tag info (i.e. '').

I would appreciate any hints on what I'm doing wrong or what I should do to avoid this extra character at the beginning.

Thanks in advance!

Upvotes: 0

Views: 182

Answers (1)

Sharcoux
Sharcoux

Reputation: 6085

The \n that you see is the place reserved in the document for the head. Be careful, it also means that the body starts at char 1. Everything you write before that will not be displayed.

If you don't need it, you can do:

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

Upvotes: 1

Related Questions