Line break in Defaultstyleddocument

Asked

Viewed 41 times

0

I’d like to know why the class DefaultStyledDocument error when inserting a line break, either by \n or by System.lineSeparator().

Minimal example:

StyleContext sc = new StyleContext();
final DefaultStyledDocument doc = new DefaultStyledDocument(sc);
final Style redStyle = sc.addStyle("RED", null);
redStyle.addAttribute(StyleConstants.Foreground, Color.RED);
jTextPane1.setDocument(doc); //esse jtext ja esa inserido no frame
doc.insertString(jTextPane1.getText().length(), "[pode ir qualquer string aqui]"+System.lineSeparator(), redStyle); //tentando pular linha com lineSeparator()

Error:

GRAVE: null
javax.swing.text.BadLocationException: Invalid insert
    at javax.swing.text.GapContent.insertString(GapContent.java:129)
    at javax.swing.text.AbstractDocument.handleInsertString(AbstractDocument.java:723)
    at javax.swing.text.AbstractDocument.insertString(AbstractDocument.java:707)

1 answer

0


Solved.

The problem was in capturing the jTextPane1.getText().length(), the correct would be doc.getLength(), apparently the line break functioned once, but in a loop the doc tried to insert in a place that was "not in it", but in the jtext.

How I’m manipulating the doc, every change has to be in it.

doc.insertString(doc.getLength(), "um texto aqui\n", blackStyle);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.