如何在 JTextArea 中将文本向右对齐? [英] How can I align text to the right in a JTextArea?

查看:97
本文介绍了如何在 JTextArea 中将文本向右对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个基于文本的冒险游戏,我试图让计算机的响应显示在左侧,而您所做的选择显示在右侧,以便轻松区分两者.问题是,我似乎找不到将文本向右对齐的方法.我在 JScrollPane 中使用了 JTextArea,所有都在 JFrame 内.

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. :)

推荐答案

您不能使用 JTextArea 来更改单个文本行的对齐方式.

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

要更改单个行的属性,最简单的方法是使用 JTextPane.类似的东西:

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

这篇关于如何在 JTextArea 中将文本向右对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆