2016-04-04 45 views
0

我正在構建一個基於文本的冒險遊戲,並且我試圖讓它使得計算機的響應位於左側,而您所做的選擇出現在右側,以便輕鬆區分這兩者。問題是,我似乎無法找到一種方法來對齊文本。我在JScrollPane內部使用了JTextArea,全部在JFrame之內。如何在JTextArea中將文本對齊到右邊?

非常感謝幫助,謝謝。 :)

+0

可能重複:喜歡的東西http://stackoverflow.com/questions/24315757/java-align-jtextarea-to-the-right – KevinO

+0

@KevinO我想這些,但它不工作。難道是因爲我正在使用'append(String)'方法嗎? –

+0

沒有足夠的信息提供有關您如何嘗試實現結果的信息。您需要分享簡潔的代碼,清楚地表明問題並清楚地解釋期望和失敗。但是,如果您的觀點是您正嘗試在同一文本區域中左右對齊文本,則必須將回復字符串的格式設置爲右對齊。 Apache Commons有實用程序可以提供幫助。我會個人使用一個JScrollPane併爲每個對話部分添加新的Widget,其中一些左對齊,右對齊。 – KevinO

回答

3

您不能使用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) {} 
+0

當我嘗試編譯時,它說它在這裏找不到變量'StyleConstants':'StyleConstants.setAlignment (左,** StyleConstants ** .ALIGN_LEFT);'但不是開頭的那個。我錯過了什麼嗎? –

+0

閱讀'StyleConstants'類的API以找出需要導入的包。 – camickr