2016-07-26 3 views
-1

나는 TextArea에 문서가 있습니다. TextField에 일치하는 단어를 강조 표시하기 위해 DocumentListener을 구현했습니다.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- whole-word-in-a-given-string-using-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

"나는"무엇을 의미합니까? 어디에서 선언 했습니까? – 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; 
    } 
} 

이 도움이됩니까?