javaswingjtextfieldjtextcomponenttext-comparison

Find a word jtextfield in java notepad


What condition should i put so that it highlights all the words in the JTextArea? This code works without the while loop but it only finds and highlights the first word match.

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);
        }
    }

Solution

  •     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.
        }