Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment

104,020

You need to use a JTextPane and use attributes. The following should center all the text:

StyledDocument doc = textPane.getStyledDocument();
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes(0, doc.getLength(), center, false);

Edit:

Vertical centering is not supported as far as I know. Here is some code you might find useful: Vertical Alignment of JTextPane

Share:
104,020
Awaken
Author by

Awaken

C/C++ embedded programmer by day, but love to keep learning by night. Got the basics of Java and C# down. Learning Ruby at the moment (trying to learn Rails as well).

Updated on March 03, 2020

Comments

  • Awaken
    Awaken over 4 years

    Is there a way to create horizontally centered text for a JTextArea like with a JTextField?

    setHorizontalAlignment(JTextField.CENTER);
    

    Is there a way I can accomplish the same thing with a multi-line text area? I can't find a method for it with JTextArea, so is there another option? JTextPane? If so, how?