Java - 将 JTextArea 向右对齐
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24315757/
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
Java - Align JTextArea to the Right
提问by Ood
I it possible to align the text inside a JTextArea to the right (or change the text alignment in general)?
我可以将 JTextArea 内的文本向右对齐(或一般更改文本对齐方式)?
|Left |
| Centered |
| Right| <- Like this
I've been searching for hours and it seems others have asked this question before but there are no good answers (that actually work).
我一直在寻找几个小时,似乎其他人之前已经问过这个问题,但没有好的答案(实际上有效)。
Thanks in advance!
提前致谢!
采纳答案by Braj
Try with JEditorPane
or JTextPane
instead of JTextArea
.
尝试使用JEditorPane
或JTextPane
代替JTextArea
。
Please have a look at my another post JEditorPane vertical aligmentfor complete sample code.
请查看我的另一篇文章JEditorPane 垂直对齐以获取完整的示例代码。
For more info have a look at this thread Vertical Alignment of Text in JEditorPane
有关更多信息,请查看此线程JEditorPane 中文本的垂直对齐
Sample code:
示例代码:
JTextPane output = new JTextPane();
SimpleAttributeSet attribs = new SimpleAttributeSet();
StyleConstants.setAlignment(attribs, StyleConstants.ALIGN_RIGHT);
output.setParagraphAttributes(attribs, true);
EDIT
编辑
You can try
你可以试试
JTextArea jTextArea = new JTextArea();
jTextArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
Read more about How to set the orientation of JTextArea from right to left
阅读更多关于如何从右到左设置 JTextArea 的方向
回答by Waroa Waroa
You have to use JTextPane, It's better than JTextAreaon this case:
你必须使用JTextPane,在这种情况下它比JTextArea更好:
try this code:
试试这个代码:
JTextPane textPane=new JTextPane();
StyledDocument style = textPane.getStyledDocument();
SimpleAttributeSet align= new SimpleAttributeSet();
StyleConstants.setAlignment(align, StyleConstants.ALIGN_RIGHT);
style.setParagraphAttributes(0, style.getLength(), align, false);
modify this code If You want to make the text:
如果要制作文本,请修改此代码:
+in the Right:
+在右边:
StyleConstants.setAlignment(align, StyleConstants.ALIGN_RIGHT);
+in the Center:
+在中心:
StyleConstants.setAlignment(align, StyleConstants.ALIGN_CENTER);
+in the Left:
+在左边:
StyleConstants.setAlignment(align, StyleConstants.ALIGN_LEFT);
Take a look at this Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment