Frage

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.

War es hilfreich?

Lösung

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

Andere Tipps

Use insertBeforeStart method from HTMLDocument. Scala example:

//set basic document structure
text = "<html><title></title><body><span id='Text'></span></body></html>"
//get Document as HTMLDocument
val htmlDoc = peer.getDocument.asInstanceOf[javax.swing.text.html.HTMLDocument]
//get span element with id=Text, before which text will be inserted
val bottomText = htmlDoc.getElement("Text")
//append function with optional line feed
def appendXml(xml:String, lineFeed:Boolean) = { htmlDoc.insertBeforeStart(bottomText, s + (if (lf) "<br>" else "" )); }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top