Java JTextPane StyleConstants 对齐不能正常工作

Java JTextPane StyleConstants Allignment does not work properly

使用下面的代码,我正在尝试根据发件人对齐邮件并为其着色。但是它会立即应用颜色,但不会像图片那样立即应用对齐。

蓝色的来自发件人,必须在左边,红色的来自其他发件人,必须在右边,橙色的来自服务器,必须居中。

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

您仅为最后一段调用 setParagraphAttributes()(doc.getLength() 且大小 =1)。而是存储消息开始偏移并将段落属性应用于插入的文本

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

在最后一个字符 +1 上调用 setParagraphAttributes :doc.setParagraphAttributes(doc.getLength(), 1... 将在下一个输入上应用样式,这意味着您不是在告诉文档 "please, put the last paragraph to the right",而是在询问 "please, put the next incoming paragraph to the right".这就是为什么你觉得在你的请求被应用之前有一个"delay"。