2016-07-26 57 views
-1

我有一個TextArea其中包含一個文檔。我實施了DocumentListener以突出顯示與TextField相匹配的單詞。HighLighting all matches words Java

此代碼所做的是突出顯示我單個單詞而不是所有匹配。即:如果我嘗試在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(); 
     } 
+1

您搜索一次,您爲什麼期望它找到多個匹配? – Idos

+0

根據你的代碼,它只會顯示第一次出現,更多你需要通過匹配其他索引來獲得其他索引 – Vickyexpert

+0

https://shekhargulati.com/2010/05/04/finding-all-the-indexes-of-a-整個詞在給定字符串使用java /和http://stackoverflow.com/questions/13326872/how-to-get-the-positions-of-all-matches-in-a-string – Idos

回答

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

什麼「我」vriable意味着什麼?在哪裏宣佈? – Cohen

+0

它的索引很抱歉,通過索引 – Vickyexpert

+0

改變它很酷,你的代碼正常工作,謝謝! – Cohen

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

這是否幫助?