【问题标题】:How can I align text to the right in a JTextArea?如何在 JTextArea 中将文本右对齐?
【发布时间】:2016-07-24 09:58:26
【问题描述】:

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

非常感谢您的帮助,谢谢。 :)

【问题讨论】:

  • @KevinO 我试过了,但它不起作用。难道是因为我使用的是append(String)方法?
  • 提供的信息不足,无法准确说明您是如何尝试实现结果的。您需要分享简洁的代码,清楚地展示问题并清楚地解释期望和失败。但是,如果您的观点是您尝试在同一文本区域中左右对齐文本,则必须将回复字符串格式化为右对齐。 Apache Commons 有实用程序可以提供帮助。我会亲自使用 JScrollPane 并为对话的每个部分附加新的小部件,一些左对齐,一些右对齐。
  • 您必须使用 JEditorPane 或 JTextPane 来执行此操作。也许更简单的方法是使用两个并排的 JTextArea、一个 JList 或一个 2 列 JTable

标签: java swing text


【解决方案1】:

您不能使用 JTextArea 来更改各行文本的对齐方式。

要更改单个行的属性,最简单的方法是使用JTextPane。比如:

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

【讨论】:

  • 当我尝试编译时,它说它在这里找不到变量StyleConstantsStyleConstants.setAlignment(left, **StyleConstants**.ALIGN_LEFT);,但不是一开始的那个。我错过了什么吗?
  • 阅读StyleConstants 类的API,找出您需要导入的包。
【解决方案2】:
jTextArea1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

试试这个代码:) 将此代码放入构造函数中。

【讨论】:

    猜你喜欢
    • 2014-08-10
    • 2013-06-14
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多