7

I it possible to align the text inside a JTextArea to the right (or change the text alignment in general)?

|Left         |
|  Centered   |
|        Right|    <- Like this

I've been searching for hours and it seems others have asked this question before but there are no good answers (that actually work).

Thanks in advance!

4
  • Are you looking for whole text alignment or only for specific text in the JTextArea?
    – Braj
    Commented Jun 19, 2014 at 20:46
  • I am looking for aligning the entire text horizontally.
    – Ood
    Commented Jun 19, 2014 at 20:48
  • Can you use JEditorPane?
    – Braj
    Commented Jun 19, 2014 at 20:49
  • Yes, I suppose that's possible.
    – Ood
    Commented Jun 19, 2014 at 20:51

2 Answers 2

12

Try with JEditorPane or JTextPane instead of JTextArea.

Please have a look at my another post JEditorPane vertical aligment for complete sample code.

For more info have a look at this thread Vertical Alignment of Text in JEditorPane

Sample code:

JTextPane output = new JTextPane();

SimpleAttributeSet attribs = new SimpleAttributeSet();
StyleConstants.setAlignment(attribs, StyleConstants.ALIGN_RIGHT);
output.setParagraphAttributes(attribs, true);

EDIT

You can try

JTextArea jTextArea = new JTextArea();
jTextArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

Read more about How to set the orientation of JTextArea from right to left

1

You have to use JTextPane, It's better than JTextArea on this case:

try this code:

JTextPane textPane=new JTextPane();
StyledDocument style = textPane.getStyledDocument();
SimpleAttributeSet align= new SimpleAttributeSet();
StyleConstants.setAlignment(align, StyleConstants.ALIGN_RIGHT);
style.setParagraphAttributes(0, style.getLength(), align, false);

modify this code If You want to make the text:

+in the Right :

StyleConstants.setAlignment(align, StyleConstants.ALIGN_RIGHT);

+in the Center :

StyleConstants.setAlignment(align, StyleConstants.ALIGN_CENTER);

+in the Left :

StyleConstants.setAlignment(align, StyleConstants.ALIGN_LEFT);

Take a look at this Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment

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