Java JTextPane StyleConstants 对齐无法正常工作

标签 java swing jtextpane

使用下面的代码,我尝试根据发件人对消息进行对齐和着色。但它会立即应用颜色,但不会像图片那样立即应用对齐。

蓝色来自发件人,必须位于左侧,红色来自其他发件人,必须位于右侧,橙色来自服务器,必须居中。

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

最佳答案

仅对最后一段调用 setParagraphAttributes()(doc.getLength() 且 size =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);

关于Java JTextPane StyleConstants 对齐无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37376267/

相关文章:

java - 运行 java 应用程序后创建并显示标签

java - 如何使用 RTFEditorKit 读取纯文本文件?

java - MOXy/JAXB 注释在 weblogic 12c 上被忽略

java - Mongodb 聚合(Java/Spring)查询以获取最后一个子元素

java - 在 libGDX 中使用首选项保存数据

Java Swing : Mouse cursor misbehaves when held over a rectangle

java - 与 JTextPane 关联的 StyledDocument 的字体

Elasticsearch:匹配查询返回错误结果(Java API)

java - FIFO 缓冲区的性能条形图

java - 任何现有的java库可以在Jmenu中用swing删除、编辑、添加文件中的某些行?