【发布时间】:2014-05-06 19:07:37
【问题描述】:
我正在尝试创建一个搜索栏,以突出显示文本区域中的相应单词。我遇到的问题是下面的代码示例仅突出显示文本区域中第一次出现的单词,即它不会扫描整个文本区域。如何使关键字的所有出现都突出显示?
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 类进行以下修复,但仍然无法正常工作。
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();
}
}
【问题讨论】:
标签: java java.util.scanner jtextfield jtextarea