2009-12-31 50 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.