以下のコードでは、送信者に応じてメッセージを整列して色付けしようとしています。しかし、色はすぐに適用されますが、画像としてすぐに配置することはできません。Java JTextPane StyleConstantsアライメントが正しく機能しない
青は送信者からのもので、左側は赤で、赤は他の送信者のもので、右側はサーバーのオレンジで、中央に配置する必要があります。
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");
}
}
次のコードで試してみてください: 'doc.setParagraphAttributes(Math.max(0、doc.getLength() - 1)、1、XXX、false);代わりに?それがうまくいくなら私はあなたに理由を説明します。 – Sharcoux