views:

265

answers:

2

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?

+3  A: 

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 support (as far as I know). Here is some custom code you might find usefull: Vertical Alignment of JTextPane

camickr
What about if I wanted to also have it vertically centered as well?
Awaken
@Awaken, See edit above:
camickr
+1  A: 

See the example of vertical alignmnet in JEditorPane/JTextPane http://java-sl.com/tip_center_vertically.html

StanislavL
Thanks for the link. Such an ordeal sadly. I wish all this were just standard stuff in Swing.
Awaken