我使用 JTextPane 作为简单的 html 编辑器。
jtp=new JTextPane();
jtp.setContentType("text/html;charset=UTF-8");
jtp.setEditorKit(new HTMLEditorKit());
当我调用 jtp.getText() 时,我得到了很好的 html 代码,所有特殊字符都被转义了。但我不想转义国家字符(波兰语),而只想转义特殊的 html 字符,如 &、<、> 当我进入编辑器时
<foo>ą ś &
我明白了
<foo>ą ś &
但我想得到
<foo>ą ś &
这怎么可能?
最佳答案
不幸的是,这是不可能的。
内部有缺陷javax.swing.text.html.HTMLWriter -- 它被硬编码为将任何非 ASCII 的符号转换为它的数字表示:
default:
if (chars[counter] < ' ' || chars[counter] > 127) {
if (counter > last) {
super.output(chars, last, counter - last);
}
last = counter + 1;
// If the character is outside of ascii, write the
// numeric value.
output("&#");
output(String.valueOf((int)chars[counter]));
output(";");
}
break;
}
无法以任何方式控制此逻辑。
但是如果您真的需要该功能,您可以做一些疯狂的事情:
- 复制粘贴HTMLWriter源到
HTMLWriterHack
(在同一个包javax.swing.text.html
中并重命名里面的所有字符串) - 将上面列出的三个
output
行替换为output(String.valueOf(chars[counter]));
- 复制粘贴HTMLDocument源到
HTMLDocumentHack
(在同一个包javax.swing.text.html
中,重命名里面的所有字符串,使其扩展HTMLDocument
并删除冲突方法) - 使用下面列出的 CustomEditorKit 而不是 HTMLEditorKit
class CustomEditorKit extends HTMLEditorKit {
@Override
public void write(Writer out, Document doc, int pos, int len) throws IOException, BadLocationException {
HTMLWriterHack writer = new HTMLWriterHack(out, (HTMLDocumentHack) doc);
writer.write();
}
@Override
public Document createDefaultDocument() {
StyleSheet styles = getStyleSheet();
StyleSheet ss = new StyleSheet();
ss.addStyleSheet(styles);
HTMLDocumentHack doc = new HTMLDocumentHack(ss);
doc.setParser(getParser());
doc.setAsynchronousLoadPriority(4);
doc.setTokenThreshold(100);
return doc;
}
}
虽然上述步骤有效(我测试过),但我当然不建议这样做。
关于Java JTextPane HTML 编辑器 UTF-8 字符编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8325109/