Java 在 JTextArea 或 JTextPane 中居中文本 - 水平文本对齐

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3213045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:28:01  来源:igfitidea点击:

Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment

javaswingjtextareajtextpane

提问by Awaken

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

有没有办法像 JTextField 一样为 JTextArea 创建水平居中的文本?

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?

有没有办法用多行文本区域完成同样的事情?我找不到使用 JTextArea 的方法,那么还有其他选择吗?JTextPane?如果是这样,如何?

采纳答案by camickr

You need to use a JTextPane and use attributes. The following should center all the text:

您需要使用 JTextPane 并使用属性。以下内容应使所有文本居中:

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

据我所知,不支持垂直居中。以下是一些您可能会觉得有用的代码:JTextPane 的垂直对齐