32

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?

Awaken
  • 1,193
  • 2
  • 13
  • 26

1 Answers1

67

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

camickr
  • 308,339
  • 18
  • 152
  • 272
  • 1
    What about if I wanted to also have it vertically centered as well? – Awaken Jul 09 '10 at 17:47
  • There are no casting problems with the code above. Note that if you are using a JEditorPane, only StyledDocument supports the setParagraphAttributes() method. You will need to cast the result of getDocument() to StyledDocument. – server_kitten May 20 '14 at 22:46
  • Not sure how this code above works but I needed to make doc.setParagraphAttributes(center, false) to make it work. – John Smith Aug 07 '15 at 19:03