Asalas77
Asalas77

Reputation: 249

How to set different JTextArea text alignment per line?

I have a JTextArea in which i want to display messages aligned to right or left, depending on a variable I pass along with the message. Can I do that?


What did I do wrong? Nothing gers added to the text pane when i run my GUI

battleLog = new JTextPane();
    StyledDocument bL = battleLog.getStyledDocument();

    SimpleAttributeSet r = new SimpleAttributeSet();
    StyleConstants.setAlignment(r, StyleConstants.ALIGN_RIGHT);

    try {
        bL.insertString(bL.getLength(), "test", r);
    } catch (BadLocationException e1) {
        e1.printStackTrace();
    }

Upvotes: 0

Views: 7467

Answers (2)

camickr
camickr

Reputation: 324207

Not with a JTextArea.

You need to use a JTextPane which supports different text and paragraph attributes. An example to CENTER the text:

JTextPane textPane = new JTextPane();
textPane.setText("Line1");
StyledDocument doc = textPane.getStyledDocument();

//  Define the attribute you want for the line of text

SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);

//  Add some text to the end of the Document

try
{
    int length = doc.getLength();
    doc.insertString(doc.getLength(), "\ntest", null);
    doc.setParagraphAttributes(length+1, 1, center, false);
}
catch(Exception e) { System.out.println(e);}

Upvotes: 2

veryyoung
veryyoung

Reputation: 1

if("left".equals(input)){
    setAlignmentX(Component.LEFT_ALIGNMENT);
}

Have a try!

Upvotes: 0

Related Questions