2016-07-26 6 views
-1

私は文書を含むTextAreaを持っています。 TextFieldに一致する単語を強調表示するためにDocumentListenerを実装しました。HighLighting all matches words Java

このコードは、すべての一致ではなく、1つの単語を強調表示します。つまり、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-指定された文字列を使用している完全な単語を使用する/と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

"私"は何を意味するのですか?どこが宣言されていますか? – 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; 
    } 
} 

は、このヘルプをしていますか?