Selection Indexes are not same to getText indexes

拟墨画扇 提交于 2019-12-25 16:43:30

问题


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.



来源:https://stackoverflow.com/questions/17073304/selection-indexes-are-not-same-to-gettext-indexes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!