簡體   English   中英

如何在JTextArea中向右對齊文本?

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

我正在構建一個基於文本的冒險游戲,並且試圖使該游戲的響應在左側,而您所做的選擇則在右側,以便於區分兩者。 問題是,我似乎找不到找到將文本右對齊的方法。 我在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) {}
jTextArea1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

嘗試以下代碼:)將此代碼放入構造函數中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM