Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment

主宰稳场 提交于 2019-11-26 07:46:22

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/3213045/centering-text-in-a-jtextarea-or-jtextpane-horizontal-text-alignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!