在JTextArea或JTextPane中居中文本 - 水平文本对齐 [英] Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment

查看:726
本文介绍了在JTextArea或JTextPane中居中文本 - 水平文本对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

setHorizontalAlignment(JTextField.CENTER);

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

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?

推荐答案

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

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);

编辑:

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

Vertical centering is not supported as far as I know. Here is some code you might find useful: Vertical Alignment of JTextPane

这篇关于在JTextArea或JTextPane中居中文本 - 水平文本对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆