2013-03-17 46 views
1

我应该放什么样的条件以便突出显示JTextArea中的所有单词? 此代码在没有while循环的情况下工作,但仅查找并突出显示第一个单词匹配。在java记事本中查找字词jtextfield

String findstr = findTextField.getText().toUpperCase(); // User Input Word to find 
int findstrLength = findstr.length();     
String findtextarea = textarea.getText().toUpperCase(); // TextArea Content 
Highlighter h = textarea.getHighlighter(); 
h.removeAllHighlights(); 
try 
    { 
     int index=0; 
     while(index>=0)        // What should I put here ?? 
     { 
      index = findtextarea.indexOf(findstr,index); 
      h.addHighlight(index,index+findstrLength, DefaultHighlighter.DefaultPainter); 
     } 
    } 

回答

2
while(index>=0) { 
     index = findtextarea.indexOf(findstr,index); 
     if (index > 0) { 
      h.addHighlight(index,index+findstrLength, DefaultHighlighter.DefaultPainter); 
     } 
     index++; // try adding this to allow you to look for the next index. 
    } 
+0

是啊!诀窍... ..它凌晨4点,我想了一个小时......没有意识到.. !!对我来说很愚蠢。谢谢 !!! – 2013-03-17 22:54:37

+0

@Sharad坦克在Oracle教程中的可编译示例 – mKorbel 2013-03-18 07:33:23