使用下面的代码,我尝试根据发件人对消息进行对齐和着色。但它会立即应用颜色,但不会像图片那样立即应用对齐。
蓝色来自发件人,必须位于左侧,红色来自其他发件人,必须位于右侧,橙色来自服务器,必须居中。
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/