Bom Tomdabil
Bom Tomdabil

Reputation: 61

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.

Help is much appreciated, Thanks. :)

Upvotes: 0

Views: 4034

Answers (2)

Shinwar ismail
Shinwar ismail

Reputation: 307

jTextArea1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

Try this code :) put this code in constructor .

Upvotes: 1

camickr
camickr

Reputation: 324207

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) {}

Upvotes: 3

Related Questions