我有两个文本文件,我试图比较,即找到匹配的单词并突出显示匹配的单词。下面的代码获取两个文件,找到匹配的单词并打印出来:
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);
}
//
}
};
例如,&#39; test.txt&#39;包含:Hello, my name is John and I live in a box.
和&#39; test1.txt&#39;包含:John does not live in France.
打印出(system.in.println
)John
,in
和live
。 pane.setPage(file.toURI().toURL());
打印出&#39; test.txt&#39;中的所有内容。在一个窗口中,这是两个不同的输出。
我想要达到的目的是突出显示匹配的单词,欣赏原始文本。因此,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 :(得分:0)
你调用highlight(pane,mtch); 所以它要求每个单词。
highlight()通过调用
删除所有先前的// First remove all old highlights
removeHighlights(textComp);
因此唯一的最后一个词突出显示