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

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

setHorizontalAlignment(JTextField.CENTER); 

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

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

 StyledDocument doc = textPane.getStyledDocument(); SimpleAttributeSet center = new SimpleAttributeSet(); StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER); doc.setParagraphAttributes(0, doc.getLength(), center, false); 

编辑:

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