2012-06-11 27 views
0

我需要從多行支持的文本組件中獲得特定的行。所以它要麼是JTextArea要麼是JTextPane獲取並寫入一些數字

如何獲得第1行,第2行或.. etc?例如從下面的文本中獲得line3

line1 
line2 
line3 
line4 

是否可以爲某些行設置另一個值?例如。設置lineNew代替line2

line1 
lineNew 
line3 
line4 

有什麼辦法?

+0

閱讀全文,並取代它作爲一個整體的文本? – fmucar

回答

2

要獲取JTextComponent中的文本,請使用getText()方法,該方法將返回String

然後獲取行,將字符串拆分爲\n

JTextArea txt = new JTextArea("line1\nline2\nline3\nline4"); 
String s = txt.getText(); 
String[] lines = s.split("\n"); 
// now to access the second line, use lines[1] 

現在如果要修改文字,可以使用setText(String)方法。

txt.setText("something else"); 

也有你可以用它來改變文字像insert(String,int)append(String)replaceRange(String,int,int)其他一些方法。所有這些都記錄在javadocs

+0

+1。你比我快:) – GETah

1

如何獲得第1行,第2行或.. etc?

通過JTextArea.getText()/JTextPane.getText()獲取從JTextArea/JTextPane文本。一旦你將文本作爲字符串,你可以通過將新行字符作爲分隔符分割文本來獲得不同的行。

0
JTextArea jText = new JTextArea("line1\nline2\nline3\nline4"); 

String temp = jText.getText(); 

String[] tempArr = temp.split("\n"); 

//方法gettext的

public String getText(int lineNos){ 

      return Str[lineNos].getText(); 

} 

//方法的setText

public void setText(int lineNos){ 

      Str[lineNos].setText("Hello"); // Can also use Scanner here 

} 
相關問題