简体   繁体   English

如何在JTextArea中向右对齐文本?

[英]How can I align text to the right in a JTextArea?

I'm building a text-based adventure game, and I'm trying to make it so that the computer's responses are on the left, while the choices you make appear on the right, so as to easily distinguish the two. 我正在构建一个基于文本的冒险游戏,并且试图使该游戏的响应在左侧,而您所做的选择则在右侧,以便于区分两者。 The problem is, I can't seem to find a way to align text to the right. 问题是,我似乎找不到找到将文本右对齐的方法。 I'm using a JTextArea inside a JScrollPane , all inside a JFrame . 我在JScrollPane内使用JTextArea ,全部在JFrame

Help is much appreciated, Thanks. 非常感谢您的帮助,谢谢。 :) :)

You can't use a JTextArea to change the alignment of individual lines of text. 您不能使用JTextArea更改文本各行的对齐方式。

To change attributes of individual lines the easiest way is to use a JTextPane . 要更改各个行的属性,最简单的方法是使用JTextPane Something like: 就像是:

JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();

SimpleAttributeSet left = new SimpleAttributeSet();
StyleConstants.setAlignment(left, StyleConstants.ALIGN_LEFT);
StyleConstants.setForeground(left, Color.RED);

SimpleAttributeSet right = new SimpleAttributeSet();
StyleConstants.setAlignment(right, StyleConstants.ALIGN_RIGHT);
StyleConstants.setForeground(right, Color.BLUE);

try
{
    doc.insertString(doc.getLength(), "\nLeft aligned text.", left );
    doc.setParagraphAttributes(doc.getLength(), 1, left, false);
    doc.insertString(doc.getLength(), "\nRight aligned text.", right );
    doc.setParagraphAttributes(doc.getLength(), 1, right, false);
    doc.insertString(doc.getLength(), "\nMore left aligned text.", left );
    doc.setParagraphAttributes(doc.getLength(), 1, left, false);
    doc.insertString(doc.getLength(), "\nMore right aligned text.", right );
    doc.setParagraphAttributes(doc.getLength(), 1, right, false);
}
catch(Exception e) {}
jTextArea1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

尝试以下代码:)将此代码放入构造函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM