2009-12-31 51 views
2

我正在嘗試使用Java Swing製作文本編輯器。在這我使用JEditorPane而不是JTextArea。我在刪除選定文本並從JEditorPane中替換選定文本時遇到問題。我使用的代碼是:刪除和替換JEditorPane中的選定文本

public void delete(JEditorPane txt) 
{ 

    int start = txt.getSelectionStart(); 
    int end = txt.getSelectionEnd(); 
    String startText = txt.getText().substring(0,start); 
    String endText = txt.getText().substring(end,txt.getText().length()); 
    txt.setText(startText + endText); 
} 

我這裏面臨的問題是,當我考慮getSelectionStart()和getSelectionEnd()的價值,他們不這樣做,但在使用子考慮換行符,正在考慮換行符。因此,如果我在一行之前使用此代碼之前有5個換行符,則不是刪除所選文本,而是從小於所選文本5的位置刪除文本。與Replace一樣。請幫忙。

+0

我覺得他們都考慮換行字符,但Windows實際上使用兩個字符作爲換行符(回車+換行),這似乎在這裏引起混亂。 – 2009-12-31 11:52:19

回答

11

使用JEditorPane.getDocument().remove()和​​

+3

當然。注意:'remove'需要'len'作爲第二個參數,所以你必須使用'end-start'。 – 2009-12-31 11:50:43

+0

謝謝,它的工作。 – Logan 2010-01-03 06:23:58

0

可以使用replaceSelection()方法,它需要一個字符串替換選定的文本。這是它的語法。當你想刪除它時,只需傳遞一個空字符串作爲參數。

jTextArea.replaceSelection(""); 
0
int l1,l2; 
l1=jTextArea1.getSelectionStart(); 
l2=jTextArea1.getSelectedText().length(); 
jTextArea1.getDocument().remove(l1, l2); 



//This Will Remove only the selected text.