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

时间:2016-04-04 18:06:48

标签: java swing text

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.

Help is much appreciated, Thanks. :)

2 个答案:

答案 0 :(得分:3)

You can't use a JTextArea to change the alignment of individual lines of text.

To change attributes of individual lines the easiest way is to use a 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) {}

答案 1 :(得分:1)

jTextArea1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

尝试此代码:) 将此代码放在构造函数中。