使用下面的代码,我试图根据发件人对消息进行对齐和着色。但是它立即应用颜色,但不立即应用对齐作为图片。
蓝色的来自发件人,必须在左边,红色的是其他发件人,必须在右边,服务器的橙色,必须居中。
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 - Java JTextPane StyleConstants分配无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37376267/