javadocumentlistener

HighLighting all match words Java


I have a TextArea which contains a document. I implemented a DocumentListener in order to highlight words that matches in the TextField.

What this code does is highlight I single word instead of all matches. i.e: if i try to search the word "move" in the TextArea, & there're repeated 3 times that word, this code just highlight the first one and no the rest, I need to highlight all words that matches!

public void search() throws BadLocationException //This method makes all logic for highLigh from jtextField into Document(TextArea)
    {
        highLighter.removeAllHighlights();
        String s = textField.getText();

        if(s.length() <= 0)
        {
            labelMessage("Nothing to search for..");
            return; //go out from this "if statement!".
        }

        String content = textArea.getText();
        int index = content.indexOf(s, 0); //"s" = the whole document, 0 = means that was found(match) or -1 if no match(no found is return -1)

        if(index >= 0) //match found
        {
            int end = index + s.length();
            highLighter.addHighlight(index, end, highlighterPainter);
            textArea.setCaretPosition(end);
            textField.setBackground(entryBgColor);
            labelMessage("'" + s + "' found. Press ESC to end search");
        }

    }

    void labelMessage(String msm)
    {
        statusLabel.setText(msm);
    }

    @Override
    public void changedUpdate(DocumentEvent e)
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void insertUpdate(DocumentEvent e)
    {
        try
        {
            search();
        } catch (BadLocationException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

Solution

  • Try below code if it help you,

        String content = textArea.getText();
    
        while(content.lastIndexOf(s) >= 0)
        {
            int index = content.lastIndexOf(s);
            int end = index + s.length;
    
            highLighter.addHighlight(index, end, highlighterPainter);
            textArea.setCaretPosition(end);
            textField.setBackground(entryBgColor);
            labelMessage("'" + s + "' found. Press ESC to end search");
    
            content = content.substring(0, index - 1);
        }