选择索引与getText索引不同 [英] Selection Indexes are not same to getText indexes
问题描述
我是Java的新手,7天前开始了一个项目,今天我和这个地方的一些人成功地解决了一个问题,但仍然还有一个问题...
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 :|
这是我的按钮代码:
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);
}
我确定我需要做一些字符串处理,以将字符串索引转换为摆动的jEditorPane/JTextPane索引
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?"
,它以这种方式突出显示:
嘿,
d o
你好吗?"
and it highlight it this way:
"Hey,
How do
you do?"
这意味着它还开始了一个索引,该索引应该是什么,在这里是\ n的临时转义字符,我不知道,这会导致它在单行文本中出现一些时间...
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...
我该如何骑呢?
推荐答案
请参见文本和换行以获取更多信息和解决方案.该链接的基础是使用:
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);
上面的代码只会返回"\ n"作为EOL字符串,因此,当您进行搜索然后选择文本时,偏移量将匹配.
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.
这篇关于选择索引与getText索引不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!