Search code examples
javaswingjtextpane

Java JTextPane StyleConstants Allignment does not work properly


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.

enter image description here

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

Solution

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