我有兩個文本文件,我試圖比較,即查找匹配的單詞並突出顯示匹配的單詞。下面的代碼利用兩個文件,找到匹配詞和打印出來:如何突出兩個文本文件中的匹配詞?
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」包含:Hello, my name is John and I live in a box.
和「test1.txt的」包含:John does not live in France.
此打印出(system.in.println
)John
,in
和live
。 pane.setPage(file.toURI().toURL());
在「test.txt」中打印出一個窗口中的所有內容,這是兩個不同的輸出。
我想要實現的是突出顯示匹配的單詞admmant原始文本。因此,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)
,並且打印出的文本文件的內容。
好吧,這又有什麼問題呢?任何錯誤?你有SSCCE重現這個問題嗎? – StanislavL
我現在把'frame.add(pane); frame.pack(); frame.setVisible(true); 突出顯示(窗格,mtch);'在內部括號內,它當前僅突出顯示原文中匹配文本的最後一個單詞。我試圖突出顯示所有匹配的文本,而不僅僅是最後一行。 – Love
例如,代碼打開一個文本窗口:「你好,我的名字是約翰,我住在一個盒子裏」,唯一突出顯示的單詞是「in」,因爲它是匹配文本的最後一個單詞。我試圖突出顯示所有匹配的單詞。 – Love