0

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();
    }
0

2 Answers 2

2

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);}
4
  • Does JtextPane accept user inputs as JTextArea does?
    – Braj
    Commented May 11, 2014 at 16:18
  • This does not work for me, nothing gets added to the text pane. See the edit in question please.
    – Asalas77
    Commented May 11, 2014 at 16:41
  • @Braj, it is like a JTextArea except it supports attributes for the text. See the Swing tutorial on Text Components Features for a more complete example of its ability to use attributes.
    – camickr
    Commented May 11, 2014 at 18:42
  • @Asalas77, Oops, the alignment attribute is a paragraph attribute so you need to set it for the whole line, not just the string you are inserting. See the code for an updated example.
    – camickr
    Commented May 11, 2014 at 19:08
0
if("left".equals(input)){
    setAlignmentX(Component.LEFT_ALIGNMENT);
}

Have a try!

2
  • wouldn't rhis change the alignment of all the lines currently in my text area? I only need to change the last one and keep the rest as it was.
    – Asalas77
    Commented May 11, 2014 at 16:20
  • The setAlignmentX(...) method is used for aligning the entire component in its parent panel, if the layout manager supports the alignment property. It has nothing to do with the text inside the text pane.
    – camickr
    Commented May 11, 2014 at 18:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.