我正在构建一个基于文本的冒险游戏,我试图让计算机的响应位于左侧,而你所做的选择出现在右侧,以便轻松区分两者。问题是,我似乎找不到一种将文本向右对齐的方法。我在 JScrollPane
内使用 JTextArea
,所有这些都在 JFrame
内。
非常感谢您的帮助,谢谢。 :)
最佳答案
您不能使用 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) {}
关于java - 如何在 JTextArea 中将文本右对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36409784/