Selection Indexes are not same to getText indexes

2019-09-06 01:50发布

问题:

i'm new to java, start a project 7 days ago, today with some folks from this place i successed to pass through one problem, but still there's one more...

in last problem i needed to search an string and highlight it, but now, my problem is:

Why selection index are not same to the indexes i search for after some unknown character which i dont know my self :|

this is my button code:

    int startFrom = jEditorPane1.getSelectionStart();
    if(jEditorPane1.getSelectionStart() == jEditorPane1.getSelectionEnd()){
        startFrom = -1;
    }

    String searchWord = jTextField3.getText();
    int searchIndex = jEditorPane1.getText().indexOf(searchWord, startFrom + 1);
    if(searchIndex != -1){
        jEditorPane1.requestFocusInWindow();
        jEditorPane1.select(searchIndex, searchIndex+searchWord.length());
    }
    else{
        jEditorPane1.setSelectionStart(0);
        jEditorPane1.setSelectionEnd(0);
    }

and i'm sure that i need to do some string processing, to convert string index to swing jEditorPane/JTextPane index

for example: i search for do in string like this: "Hey, How do you do?"

and it highlight it this way: "Hey, How doyou do?"

which mean it started one index forther that what it should, and in here it's casue escape char of \n and i dont know, cause some time it happen in single row text...

how can i get ride of this?

回答1:

See Text and New Lines for more information and a solution. The basics of this link is to use:

int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);

The above will only return "\n" as the EOL string so the offsets will match when you do a search and then select the text.