Java JTextPane HTML编辑器UTF-8字符编码
我正在使用JTextPane作为简单的html编辑器。
I'm using JTextPane as simple html editor.
jtp=new JTextPane();
jtp.setContentType("text/html;charset=UTF-8");
jtp.setEditorKit(new HTMLEditorKit());
当我调用jtp.getText()时,我获得了很好的html代码,所有特殊字符都被转义。但是我不希望逃脱国家角色(波兰语),但只有特殊的html字符如&,<,>
当我进入编辑器时
When I call jtp.getText() I get nice html code with all special chars escaped. But I don't want escape national characters (polish) but only special html chars like &, <, > When I enter in editor
<foo>ą ś &
我得到
<foo>ą ś &
但我希望得到
<foo>ą ś &
它是如何实现的?
不幸的是,这是不可能的。
That's not possible, unfortunately.
javax.swing.text.html.HTMLWriter - 将任何非ASCII符号转换为数字表示是硬编码的:
There's a flaw inside javax.swing.text.html.HTMLWriter -- it is hardcoded to convert any symbol that is not ASCII to its numeric representation:
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;
}
无法以任何方式控制此逻辑。
This logic cannot be controlled in any way.
但如果你真的非常需要这种功能,你可以做疯狂的事情:
BUT If you really really need that functionality you could do the crazy stuff:
- 复制并粘贴 HTMLWriter 来源于
HTMLWriterHack
(在同一个包中javax.swing.text.html
并重命名里面的所有字符串) - 替换上面列出的三个
输出
类似输出的行(String.valueOf(chars [counter]));
- 复制并粘贴 HTMLDocument 来源
HTMLDocumentHack
(在同一个包中javax.swing.text.html
,renami内部所有字符串,使其扩展HTMLDocument
并删除冲突方法) - 使用下面列出的CustomEditorKit而不是HTMLEditorKit
- copy and paste HTMLWriter sources into
HTMLWriterHack
(in the same packagejavax.swing.text.html
and renaming all strings inside) - Replace the above listed three
output
lines with something likeoutput(String.valueOf(chars[counter]));
- copy and paste HTMLDocument sources into
HTMLDocumentHack
(in the same packagejavax.swing.text.html
, renaming all strings inside, making it extendHTMLDocument
and removing *ing methods) - Use the CustomEditorKit listed below instead of 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;
}
}
虽然上面的步骤(我测试过),但我当然不建议这样做。
Although the steps above work (I tested it), I certainly wouldn't recommend doing that.