HighLighting所有匹配单词Java

时间:2016-07-26 12:38:21

标签: java documentlistener

我有一个包含文档的TextArea。我实施了DocumentListener以突出显示TextField中匹配的字词。

这段代码的作用是突出我单个单词而不是所有匹配。即:如果我尝试搜索TextArea中的“移动”一词,&这个单词重复了3次,这段代码只突出显示第一个,没有其余的,我需要突出显示匹配的所有单词!

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

2 个答案:

答案 0 :(得分:1)

如果对您有帮助,请尝试以下代码,

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

答案 1 :(得分:0)

final String s = textField.getText();

String content = textArea.getText();
boolean  b = content.contains(s);  
while (b) {
    int start = content.indexOf(stringToMatch);
    int end = start + s.length() -1;

    // Write your lighlighting code here

    if (content.length() >= end ) {
      content = content.substring(end, content.length()) ;
      b = content.contains(s);
    } else {
      b = false;
    }
}

这有帮助吗?