【问题标题】:Java - Align JTextArea to the RightJava - 将 JTextArea 向右对齐
【发布时间】:2014-08-10 12:46:09
【问题描述】:

我可以将 JTextArea 内的文本向右对齐(或通常更改文本对齐方式)吗?

|Left         |
|  Centered   |
|        Right|    <- Like this

我一直在寻找几个小时,似乎其他人以前问过这个问题,但没有好的答案(实际上有效)。

提前致谢!

【问题讨论】:

  • 您是在寻找整个文本对齐方式还是只寻找JTextArea 中的特定文本?
  • 我正在寻找水平对齐整个文本。
  • 你能用JEditorPane吗?
  • 是的,我想这是可能的。

标签: java swing alignment jtextarea


【解决方案1】:

尝试使用JEditorPaneJTextPane 而不是JTextArea

请查看我的另一篇帖子 JEditorPane vertical aligment 以获取完整的示例代码。

欲了解更多信息,请查看此主题Vertical Alignment of Text in JEditorPane

示例代码:

JTextPane output = new JTextPane();

SimpleAttributeSet attribs = new SimpleAttributeSet();
StyleConstants.setAlignment(attribs, StyleConstants.ALIGN_RIGHT);
output.setParagraphAttributes(attribs, true);

编辑

你可以试试

JTextArea jTextArea = new JTextArea();
jTextArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

阅读更多关于How to set the orientation of JTextArea from right to left

【讨论】:

    【解决方案2】:

    你必须使用JTextPane,在这种情况下它比JTextArea更好:

    试试这个代码:

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

    修改此代码如果要制作文字:

    +在

    StyleConstants.setAlignment(align, StyleConstants.ALIGN_RIGHT);
    

    +在中心

    StyleConstants.setAlignment(align, StyleConstants.ALIGN_CENTER);
    

    +在

    StyleConstants.setAlignment(align, StyleConstants.ALIGN_LEFT);
    

    看看这个Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment

    【讨论】:

      猜你喜欢
      • 2016-07-24
      • 1970-01-01
      • 2014-03-15
      • 1970-01-01
      • 2021-08-26
      • 2011-09-03
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多