Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment

前端 未结 1 1922
我在风中等你
我在风中等你 2020-11-27 07:33

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

setHorizontalAlignment(JTextField.CENTER);

Is

相关标签:
1条回答
  • 2020-11-27 08:10

    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

    0 讨论(0)
提交回复
热议问题