2012-07-15 3 views
0

textPane에서 문자열을 검색 할 때 검색되는 각 행 번호에 대해 추가 색인을 얻는 이상한 문제가 있습니다 (적어도 그렇게 보입니다). StyledDoc 구절을 사용하면 textPane에서 텍스트를 가져올 때 반환됩니다. 나는 같은 창에서 같은 텍스트를 얻습니다. 그냥 평범한 텍스트에서 온 것입니다. 다른 하나는 스타일이 지정된 문서에서옵니다. 나는 여기서 뭔가를 놓친다. 내가 작업하고있는 두 버전 사이에 많은 변경 사항을 나열하려고 노력할 것입니다. StyledDocument 각 파일 행에 대해 indexof에 추가 카운트를 추가합니다.

는 일반 텍스트 버전 :

public int displayXMLFile(String path, int target){ 
    InputStreamReader inputStream; 
    FileInputStream fileStream; 
    BufferedReader buffReader; 

    if(target == 1){ 

     try{     
      File file = new File(path); 
      fileStream = new FileInputStream(file); 
      inputStream = new InputStreamReader(fileStream,"UTF-8"); 
      buffReader = new BufferedReader(inputStream); 
      StringBuffer content = new StringBuffer(""); 
      String line = ""; 
      while((line = buffReader.readLine())!=null){ 
       content.append(line+"\n"); 
      } 
      buffReader.close(); 
      xhw.txtDisplay_1.setText(content.toString()); 
     } 
     catch(Exception e){ 
      e.printStackTrace(); 
      return -1; 
     } 
    } 
} 

서식 첨부 문서 구절

protected void openFile(String path, StyledDocument sDoc, int target) 
       throws BadLocationException { 

    FileInputStream fileStream; 
    String file; 
    if(target == 1){ 
     file = "Openning First File"; 
    } else { 
     file = "Openning Second File"; 
    } 


    try { 
     fileStream = new FileInputStream(path); 

     // Get the object of DataInputStream 
     //DataInputStream in = new DataInputStream(fileStream); 

     ProgressMonitorInputStream in = new ProgressMonitorInputStream(
       xw.getContentPane(), file, fileStream); 
     BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
     String strLine; 

     //Read File Line By Line 
     while ((strLine = br.readLine()) != null) {     
      sDoc.insertString(sDoc.getLength(), strLine + "\n", sDoc.getStyle("regular")); 
     xw.updateProgress(target); 
     } 

     //Close the input stream 
     in.close(); 
    } catch (Exception e){//Catch exception if any 
     System.err.println("Error: " + e.getMessage()); 
    } 

(적용되는 스타일 제외) 이것은 내가 검색 방법 :

public int searchText(int sPos, int target) throws BadLocationException{ 

    String search = xhw.textSearch.getText(); 
    String contents; 
    JTextPane searchPane; 

    if(target == 1){ 
     searchPane = xhw.txtDisplay_1;    
    } else { 
     searchPane = xhw.txtDisplay_2; 
    } 

    if(xhw.textSearch.getText().isEmpty()){ 
     xhw.displayDialog("Nothing to search for"); 
     highlight(searchPane, null, 0,0); 
    } else { 


     contents = searchPane.getText(); 

     // Search for the desired string starting at cursor position 
     int newPos = contents.indexOf(search, sPos); 

     // cycle cursor to beginning of doc window 
     if (newPos == -1 && sPos > 0){ 
      sPos = 0; 
      newPos = contents.indexOf(search, sPos); 
     } 

     if (newPos >= 0) { 
      // Select occurrence if found 

      highlight(searchPane, contents, newPos, target); 

      sPos = newPos + search.length()+1; 
     } else { 
      xhw.displayDialog("\"" + search + "\"" + " was not found in File " + target); 
     } 
    } 
    return sPos; 
} 

샘플 파일 :

<?xml version="1.0" encoding="UTF-8"?> 
<AlternateDepartureRoutes> 
    <AlternateDepartureRoute> 
    <AdrName>BOIRR</AdrName> 
    <AdrRouteAlpha>..BROPH..</AdrRouteAlpha> 
    <TransitionFix> 
     <FixName>BROPH</FixName> 
    </TransitionFix> 
    </AlternateDepartureRoute> 
    <AlternateDepartureRoute> 
</AlternateDepartureRoutes> 

그리고 내 하이 라이터 :

public void highlight(JTextPane tPane, String text, int position, int target) throws BadLocationException { 
    Highlighter highlighter = new DefaultHighlighter(); 
    Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.LIGHT_GRAY); 
    tPane.setHighlighter(highlighter); 

    String searchText = xhw.textSearch.getText(); 
    String document = tPane.getText(); 
    int startOfSString = document.indexOf(searchText,position); 

    if(startOfSString >= 0){ 
     int endOfSString = startOfSString + searchText.length(); 
     highlighter.addHighlight(startOfSString, endOfSString, painter); 
     tPane.setCaretPosition(endOfSString); 
     int caretPos = tPane.getCaretPosition(); 
     javax.swing.text.Element root = tPane.getDocument().getDefaultRootElement(); 
     int lineNum = root.getElementIndex(caretPos) +1; 
     if (target == 1){ 
      xhw.txtLineNum1.setText(Integer.toString(lineNum)); 
     } else if (target == 2){ 
      xhw.txtLineNum2.setText(Integer.toString(lineNum)); 
     } else { 
      xhw.txtLineNum1.setText(null); 
      xhw.txtLineNum2.setText(null); 
     } 

    } else { 
     highlighter.removeAllHighlights(); 
    } 

} 

서식 첨부 문서로 검색 할 때 내가 같이 IndexOf() 나는 (그것을 반환해야 무엇을하는) 일반 텍스트 (40)를 얻고 (41)와 Alt 키에 대한 검색을 수행 할 때 . 그리고 Alt가 나타나는 줄이 추가 될 때마다 indexof() 호출이 3 행에서 2를 더 반환하도록 추가 색인을 얻습니다. 이것은 발견 된 모든 추가 행에 대해 _ 생합니다. 나는 명백한 것을 놓치고 있는가? (이것을 더 작은 단일 클래스로 푸시해야 체크가 더 쉽도록 할 수 있습니다. 나중에 더 많은 시간이있을 때 가능합니다).

미리 감사드립니다 ...

답변

0

확인 해결책 (기본)을 찾았습니다. 나는 두 변수 "newPos"& "newPosS"를 비교할 때

String search = xw.textSearch.getText(); 
    String contents; 
    String contentsS; 
    JTextPane searchPane; 
    StyledDocument sSearchPane; 

    searchPane = xw.txtDisplay_left; 
    sSearchPane = xw.txtDisplay_left.getStyledDocument(); 


    contents = searchPane.getText(); 
    contentsS = sSearchPane.getText(0, sSearchPane.getLength()); 

    // Search for the desired string starting at cursor position 
    int newPos = contents.indexOf(search, sPos); 
    int newPosS = contentsS.indexOf(search, sPos); 

그래서, newPos이 newPosS 후 1 이상을 retruned ... 나는 두 가지 방법으로 동일한 텍스트 componet에서 텍스트를 얻고 측면에서이 문제를 접근 검색 문자열이 발견 된 각 행에 대해 따라서 샘플 파일을보고 "Alt"를 검색하면 첫 번째 인스턴스가 2 행에 있습니다. "newPos"는 41을 반환하고 "newPosS는 40을 반환합니다 (올바른 텍스트를 강조 표시합니다). 다음 행 (행에서 발견됨) 3) "newPos"는 71을 반환하고 "newPosS"는 69를 반환합니다. 보시다시피, 모든 새 행은 발생이 시작되는 행 번호만큼 카운트를 증가시킵니다. 새 행마다 추가 문자가 추가 될 것으로 생각됩니다. StyledDoc에 존재하지 않는 textPane에서.

나는 합리적인 explaination가 확신하지만이 시간에 그것을 필요가 없습니다. 당신이 윈도우에있는 경우

1

, 다음 TextComponent에 텍스트 (searchPane.getText())에는 캐리지 리턴 + 개행 문자 (\ r \ n)가 포함될 수 있지만 TextComponent의 스타일이 지정된 문서 (sSearchPane.getText (0, sSearchPane.getLength()))에는 개행 문자 (\ n) 만 포함됩니다. 그래서 newPos는 newPosS보다 항상 그 시점에있는 개행 수만큼 큽니다.이 문제를 해결하려면 검색 기능에서 다음을 변경할 수 있습니다

contents = searchPane.getText(); 

에 :

contents = searchPane.getText().replaceAll("\r\n","\n"); 

검색이 서식 첨부 문서가 사용하는 동일한 인덱스 발생 그 방법을.