我正在尝试创建一个搜索栏,突出显示文本区域中的相应单词。我有的问题是下面的代码示例只突出显示文本区域中第一个出现的单词,即它不扫描整个文本区域。我该如何做到这一点,以便突出显示所有关键字?通过jTextArea扫描单词
public void keywordSearch() {
hilit.removeAllHighlights();
String keyword = txtSearch.getText();
String content = txtArea.getText();
int index = content.indexOf(keyword, 0);
if (index >= 0) { // if the keyword was found
try {
int end = index + keyword.length();
hilit.addHighlight(index, end, painter);
txtSearch.setBackground(Color.WHITE);
} catch (BadLocationException e) {
e.printStackTrace();
}
} else {
txtSearch.setBackground(ERROR_COLOR);// changes the color of the text field if the keyword does not exist
}
}
我曾尝试使用扫描仪类以下修补程序,但它仍然无法正常工作。
Scanner sc = new Scanner(content);
if (index >= 0) { // if the keyword was found
try {
while(sc.hasNext() == true)
{
int end = index + keyword.length();
hilit.addHighlight(index, end, painter);
txtSearch.setBackground(Color.WHITE);
sc.next();
}
任何帮助,非常感谢。提前致谢。使用while循环(进入无限循环)
修复
while(index >= 0) { // if the keyword is found
try {
int end = index + keyword.length();
hilit.addHighlight(index, end, painter);
txtSearch.setBackground(Color.WHITE);
index = content.indexOf(keyword, index);
System.out.println("loop");// test to see if entered infinite loop
} catch (BadLocationException e) {
e.printStackTrace();
}
}
试过这个,但它进入了一个无限循环。 – user3469429
@ user3469429您可能需要从第二个索引+ 1进行扫描。 –