2014-03-27 54 views
0

我正在尝试创建一个搜索栏,突出显示文本区域中的相应单词。我有的问题是下面的代码示例只突出显示文本区域中第一个出现的单词,即它不扫描整个文本区域。我该如何做到这一点,以便突出显示所有关键字?通过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(); 
     } 
    } 

回答

1

的关键是在这里:

int index = content.indexOf(keyword, 0); 
if (index >= 0) { // if the keyword was found 

更改为一个while循环从索引中再次搜索,你第一时间发现:

int index = content.indexOf(keyword, 0); 
while (index >= 0) { // if the keyword was found 
    // Do stuff 
    index = content.indexOf(keyword, index); 
} 

您还需要更改您的最终else以做另一个检查,看它是否根本不存在(有几种方法可以做到这一点)。

+0

试过这个,但它进入了一个无限循环。 – user3469429

+0

@ user3469429您可能需要从第二个索引+ 1进行扫描。 –

0

你只是在寻找一个单词的发生。

... 
for(int i = 0; i < content.length(); i++){ 

    int index = content.indexOf(keyword, i); 
    if (index >= 0) { // if the keyword was found 

    int end = index + keyword. 
    hilit.addHighlight(index, end, painter); 
    txtSearch.setBackground(Color.WHITE); 

    } 
... 

这个for-loop将搜索整个conent-string并将关键字的所有出现都发送到addHighlight-method。

+0

呃。不要这样做。它会“起作用”,因为它确实会突出显示每个单词,但它效率非常低,因为您会一遍又一遍地重复查找和突出显示同一个单词。 –

0
... 
ArrayList<Integer> keywordIndexes = new ArrayList<Integer>(); 
int index = content.indexOf(keyword, 0); 
for(int i = 0; i < content.length(); i++){ 
    if (index >= 0) { // if keyword found 

    int end = index + keyword.length(); 
    keywordIndexes.add(index); // Add index to arraylist 
    keywordIndexes.add(end); // Add end to next slot in arraylist 
} 

for(int j = 0; j < keywordIndexes.size(); j+=2){ 
    hilit.addHighlight(j, (j+1), painter); 
    txtSearch.setBackground(Color.WHITE); 
} 
... 

这可能不是最优化的代码,但它应该工作。