2016-05-22 3 views
0

以下のコードでは、送信者に応じてメッセージを整列して色付けしようとしています。しかし、色はすぐに適用されますが、画像としてすぐに配置することはできません。Java JTextPane StyleConstantsアライメントが正しく機能しない

青は送信者からのもので、左側は赤で、赤は他の送信者のもので、右側はサーバーのオレンジで、中央に配置する必要があります。

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

次のコードで試してみてください: 'doc.setParagraphAttributes(Math.max(0、doc.getLength() - 1)、1、XXX、false);代わりに?それがうまくいくなら私はあなたに理由を説明します。 – Sharcoux

答えて

2

あなたは最後の段落だけ(doc.getLength()およびサイズ= 1)のためのsetParagraphAttributes()を呼び出します。 doc.setParagraphAttributes(doc.getLength(), 1...、その代わりに、あなたの文書を伝える」という意味、次の入力にスタイルをしてください適用されます。代わりに、店のメッセージは、最後の文字+ 1にsetParagraphAttributesを呼び出すと、オフセットおよび挿入されたテキスト

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

これも動作します、ありがとう – Ilkin

1

に段落属性を適用開始します最後の段落を右に置いてください。 "代わりに"次の段落を右に置いてください "と尋ねてきます。あなたのリクエストが適用される前に「遅れ」があると感じている理由です。

関連する問題