Reputation: 396
With code below I'm trying to align and color messages according to sender. But it applies color immediately however it does not apply alignment immediately as the picture.
blue ones are from sender and must be on the left, red ones are from other senders, must be on the right, orange from server, must be centered.
public void showMessage(String name, String message) {
StyledDocument doc = txt_showMessage.getStyledDocument();
SimpleAttributeSet left = new SimpleAttributeSet();
StyleConstants.setAlignment(left, StyleConstants.ALIGN_LEFT);
StyleConstants.setForeground(left, Color.RED);
StyleConstants.setFontSize(left, 14);
SimpleAttributeSet right = new SimpleAttributeSet();
StyleConstants.setAlignment(right, StyleConstants.ALIGN_RIGHT);
StyleConstants.setForeground(right, Color.BLUE);
StyleConstants.setFontSize(right, 14);
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
StyleConstants.setForeground(center, Color.ORANGE);
try {
if (c.getServerName().equals(name)) {
doc.insertString(doc.getLength(), new SimpleDateFormat("HH:mm").format(new Date()) + " " + name + ": " + message + "\n", center);
doc.setParagraphAttributes(doc.getLength(), 1, center, false);
} else if (c.getName().equals(name)) //if message is from same client
{
doc.insertString(doc.getLength(), new SimpleDateFormat("HH:mm").format(new Date()) + " " + name + ": " + message + "\n", right);
doc.setParagraphAttributes(doc.getLength(), 1, right, false);
} else { //if message is from another client
doc.insertString(doc.getLength(), new SimpleDateFormat("HH:mm").format(new Date()) + " " + name + ": " + message + "\n", left);
doc.setParagraphAttributes(doc.getLength(), 1, left, false);
}
} catch (BadLocationException e) {
System.out.println("Cannot write message");
}
}
Upvotes: 0
Views: 769
Reputation: 6085
Calling setParagraphAttributes on the last character+1 : doc.setParagraphAttributes(doc.getLength(), 1...
will apply the style on the next input, meaning that instead of telling your document "please, put the last paragraph to the right", you're asking instead "please, put the next incoming paragraph to the right". That's why you feel that there is a "delay" before your request is applied.
Upvotes: 1
Reputation: 57381
You call setParagraphAttributes() for the last paragraph only (doc.getLength() and size =1). Instead store message start offset and apply the paragraph attributes to the inserted text
int offset = doc.getLength();
String message = new SimpleDateFormat("HH:mm").format(new Date()) + " " + name + ": " + message + "\n"
doc.insertString(doc.getLength(), message, center);
doc.setParagraphAttributes(offset, message.length() , center, false);
Upvotes: 2