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?
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.
Just use the setBounds attribute. Jtextfield. setBounds(x,x,x,x);
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With