Search code examples
javahtmljeditorpaneappendtext

How to use insertString to append a line on a JEditorPane with HTML


What's the difference between this

conversationPane.setText(msg + conversationPane.getText());

and this?

conversationPane.setText(conversationPane.getText() + msg);

I know thah the second line does not print the message but Why!? I'm making a chat and the new messages should appear below the previous message (Like in a normal chat) but with the first line the new messages appear up all the conversation.

I use JEditorPane whith content type HTML because the chat contents smileys and this things, if I change the content type to textPlain the second line works perfectly.

I'm looking for the solution and find things with insertString using a Document and Attributes but I don't undestand how used and if this can solve my problem.


Solution

  • I don't know exactly why. I know, however, it's related with text being appended after a </html> tag. When you setText() on a JEditorPane with text/html content type, <html> tags are automatically added.

    I dealt with a similar problem before. The way I fixed it was saving all the text in a string, then setting it in the pane:

    String s = "";
    ...
    s += msg;
    conversationPane.setText(s);