开发者

Deleting and replacing selected text in JEditorPane

I am trying to make a Text Editor using Java Swing. I开发者_运维知识库n that I am using JEditorPane instead of JTextArea. I am facing problems in deleting selected text and replacing selected text from the JEditorPane. The Code I am Using is:

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);
}

The problem I am facing here is that, when I consider the value from getSelectionStart() and getSelectionEnd(), They don't consider newline character, but while using substring, newline character is being considered. So if I use this code on a line before which there are 5 newline characters, then instead of deleting selected text, text gets deleted from a position which is 5 less then the selected text. Same is happening with Replace. Please Help.


Use JEditorPane.getDocument().remove() and JEditorPane.getDocument().insertString()


You can use the replaceSelection() method that takes a string to replace the selected text. Here is it's syntax. When you want to delete it, simply pass an empty string as parameter.

jTextArea.replaceSelection("");


int l1,l2;
l1=jTextArea1.getSelectionStart();
l2=jTextArea1.getSelectedText().length();
jTextArea1.getDocument().remove(l1, l2);



//This Will Remove only the selected text.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜