Search code examples
javaswingjtextpanestyleddocument

How to append a string in java swing JTextPane?


I am creating a chat application. In this chat application, I have to use Java Swing's JTextPane to give style to some specific strings like the user's display name and the message's time. That's why I chose JTextPane over JTextArea. In JTextPane, I can't append the String, so I create a String buffer to append the String, then I do jTextPane.setText(stringBuffer.toString()).

Here is my problem: When I append a string into the JTextPane via a StringBuffer, there is a delay. How can I append a string line-by-line in a JTextPane?


Solution

  • Found another similar question whose answer made use of the StyledDocument and calls insertString() method on the instance of StyledDocument to append text to it and then write the StyledDocument back to JTextPane: JTextPane appending a new string