我正在阅读HTML文档作为文本,并从基于字符串数组的文档中提取匹配的字符串(带有开始和结束索引)。现在我必须更改原始HTML文档中提取的字符串的背景颜色。但我不应该更改HTML文件的格式。
所以我使用“javax.swing.text.DefaultHighlighter.DefaultHighlightPainter”,它不会改变文档的格式。突出显示后,我在本地保存文件,然后在浏览器中查看颜色。我不想使用任何编辑器,因为我的目的是在浏览器中查看。但颜色的变化并没有反映在这里,我没有解决问题的位置。这是我的代码示例。
public class TestEditer {
public static void main(String[] args) throws IOException, BadLocationException {
JEditorPane editor = new JEditorPane();
StringWriter writer = new StringWriter();
String output;
HTMLEditorKit htmlKit = new HTMLEditorKit();
List<Pattern> patternList = new ArrayList<Pattern>();
output = new Scanner(new File("C:/test.in")).useDelimiter("\\Z").next();//26787.in contains HTML text
editor.setText(output);
Document document = editor.getDocument();
String doc= document.getText(0, document.getLength());
System.out.println(document);
String[] names={"Shannon","Sperling","Kim","Tammy","Nancy","Lana"};
for (int i=0; i<names.length; i++)
{
String st = names[i];
Pattern p= Pattern.compile(st);
patternList.add(p);
}
System.out.println(patternList);
for (int i=0; i<patternList.size(); i++)
{
Matcher matcher = patternList.get(i).matcher(editor.getText());
int mStartPos=0;
int mEndPos=0;
while (matcher.find())
{
String matched = matcher.group();
System.out.println(matched);
mStartPos = matcher.start();
mEndPos = matcher.end();
System.out.println(mStartPos+" "+mEndPos);
DefaultHighlightPainter highlightPainter =new DefaultHighlightPainter(Color.RED);
editor.getHighlighter().addHighlight(mStartPos+1, mEndPos,
highlightPainter);
}
}
//htmlKit.write(writer, editor.getDocument(),0,editor.getDocument().getLength());
//String s=editor.getText();
File file = new File("C:/data/file.in");
editor.getEditorKit().write(writer,document,0,document.getLength());
String s1 = writer.toString();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(s1);
bw.close();
}