2016-06-08 2 views
0

나는 두 단어의 텍스트 파일을 비교하려고합니다. 즉 일치하는 단어를 찾아서 일치하는 단어를 강조 표시합니다. 아래의 코드는 일치하는 단어를 발견, 두 파일을 소요하고 그들을 밖으로 인쇄 : Hello, my name is John and I live in a box.와 '있는 test1.txt'가 포함되어 있습니다 :두 텍스트 파일에서 일치하는 단어를 강조 표시하는 방법은 무엇입니까?

public class Test { 

static MyHighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red); 

public static void main(String[] args) throws Exception { 
    //BufferedReader db = new BufferedReader(new FileReader("src/project/test1.txt")); 

      JFrame frame = new JFrame(); 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

      JEditorPane pane = new JEditorPane(); 

       File file = new File("src/project/test1.txt"); 
       Scanner fileScan = new Scanner(file); 

       File file1 = new File("src/project/test.txt"); 
      Scanner file1Scan = new Scanner(file1); 

      Set<String> db = new HashSet<>(); 
      Highlighter highlighter = pane.getHighlighter(); 


      while(fileScan.hasNextLine()){ 
       db.add(fileScan.nextLine());} 
       while(file1Scan.hasNextLine()){ 
        String mtch = file1Scan.nextLine(); 
        if(db.contains(mtch)){       
         pane.setPage(file.toURI().toURL()); 
         pane.setText(pane.getText() +"\n "); 
         System.out.println(mtch); 
         frame.add(pane); 
         frame.pack(); 
         frame.setVisible(true); 
         highlight(pane,mtch); 

        } 


     // 

     } 


}; 

예를 들어, 'TEST.TXT'가 포함 John does not live in France.

이것은 출력한다 (system.in.println) John, inlive. pane.setPage(file.toURI().toURL());은 'test.txt'에있는 모든 내용을 창에 출력하므로 두 가지 출력이 있습니다.

내가 달성하고자하는 것은 일치하는 단어 admist 원래 텍스트를 강조하는 것입니다. 따라서 Hello, my name is John and I live in a box.에는 John, in and live이 강조 표시됩니다. 내가 웹에서 볼 수있는 하이라이트 방법을 사용하여 하이라이트를 사용하여 테스트하고 있습니다

은 :

public static void highlight(JTextComponent textComp, String pattern) { 
     // First remove all old highlights 
     removeHighlights(textComp); 

    try { 
     Highlighter hilite = textComp.getHighlighter(); 
     Document doc = textComp.getDocument(); 
     String text = doc.getText(0, doc.getLength()); 
     int pos = 0; 

     // Search for pattern 
     while ((pos = text.indexOf(pattern, pos)) >= 0) { 
      // Create highlighter using private painter and apply around pattern 
      hilite.addHighlight(pos, pos + pattern.length(), myHighlightPainter); 
      pos += pattern.length(); 
     } 
    } catch (BadLocationException e) { 
    } 
} 

// Removes only our private highlights 
public static void removeHighlights(JTextComponent textComp) { 
    Highlighter hilite = textComp.getHighlighter(); 
    Highlighter.Highlight[] hilites = hilite.getHighlights(); 

    for (int i = 0; i < hilites.length; i++) { 
     if (hilites[i].getPainter() instanceof MyHighlightPainter) { 
      hilite.removeHighlight(hilites[i]); 
     } 
    } 
} 
} 

class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter { 

public MyHighlightPainter(Color color) { 
    super(color); 
} 

나는 highlight(pane,mtch) 시도하고 그 텍스트 파일의 내용을 출력합니다.

+0

확인을 강조

// First remove all old highlights removeHighlights(textComp); 

에 의해 이전의 모든 것들을 제거하고, 문제는 무엇인가? 오류가 있습니까? 문제를 재현하기 위해 SSCCE가 있습니까? – StanislavL

+0

나는 현재'frame.add (pane);을 넣었습니다. frame.pack(); frame.setVisible (true); (pane, mtch); '는 대괄호 안에 있고 현재 원본 텍스트 안에있는 일치하는 텍스트의 마지막 단어 만 강조 표시합니다. 마지막 줄뿐만 아니라 모든 일치하는 텍스트를 강조 표시하려고합니다. – Love

+0

예를 들어, 코드는 'Hello, my name is John and I live in a box'라는 텍스트가있는 창을 열고 일치하는 텍스트의 마지막 단어이기 때문에 강조 표시된 유일한 단어는'in'입니다. 일치하는 모든 단어를 강조 표시하려고합니다. – Love

답변

0

하이라이트 (pane, mtch)를 호출합니다. 그래서 각 단어에 대해 호출됩니다.

하이라이트는()를 호출하여 유일한 마지막 단어가

+0

죄송합니다, 조금 혼란 스럽습니다. 이전에 제거한 removeHighlights (textComp);를 주석 처리합니까? – Love

+0

감사합니다. 나는 pane.setText (pane.getText() + "\ n");를 삽입하는 실수를 보았고 그것을 제거하고'removeHighlight' 메서드를 주석 처리했습니다. – Love

관련 문제