Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment

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?

like image 577
Awaken Avatar asked Jul 09 '10 13:07

Awaken


People also ask

What is the difference between JTextPane and JTextArea?

JTextComponent, with JTextPane coming as a subclass of JEditorPane. From this, it is safe to conclude that JTextPane is a specialized form of JEditorPane which comes with some extra functionality. JTextArea comes with specific functions; one of these prevents it from wrapping text whenever the text is put in.

How do I center text in a Jtextfield?

Just use the setBounds attribute. Jtextfield. setBounds(x,x,x,x);

What is JTextPane?

A JTextPane is a subclass of JEditorPane. A JTextPane is used for a styled document with embedded images and components. A JTextPane is a text component that can be marked up with the attributes that are represented graphically and it can use a DefaultStyledDocument as the default model.

What is JTextArea in Java?

A JTextArea is a multi-line area that displays plain text. It is intended to be a lightweight component that provides source compatibility with the java. awt. TextArea class where it can reasonably do so.


1 Answers

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

like image 175
camickr Avatar answered Oct 14 '22 00:10

camickr