我正在将 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();
}