【问题标题】:Does JEditorPane have Charset problems when showing HTML?JEdi​​torPane 在显示 HTML 时是否存在字符集问题?
【发布时间】:2009-09-14 19:53:59
【问题描述】:

我有以下代码:

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;


public class ScratchPad {

    public static void main(String args[]) throws Exception {
        String html ="<html>"+
"<head>"+
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"/>"+ // this is the problem right here
"<title>Error 400 BAD_REQUEST</title>"+
"</head>"+
"<body>"+
"<h2>HTTP ERROR: 400</h2><pre>BAD_REQUEST</pre>"+
"<p>RequestURI=null</p>"+
"<p><i><small><a href=\"http://jetty.mortbay.org\">Powered by jetty://</a></small></i></p>"+
"</body>"+
"</html>";
        JFrame f = new JFrame();
        JEditorPane editor = new JEditorPane();
        editor.setEditable( false );
        editor.getDocument().putProperty( "Ignore-Charset", "true" );  // this line makes no difference either way
        editor.setContentType( "text/html" );
        editor.setText( html );

        f.add( new JScrollPane(editor, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) );
        f.pack();
        f.setVisible( true );
    }

}

如果你运行它,你会注意到框架是空白的。但是,如果我从元标记中删除“; charset=ISO-8859-1”,就会显示 HTML。任何想法为什么以及我可以做些什么来防止这种情况(除了手动破解我无法控制的 HTML 字符串......)。

Edit #1 - 不幸的是 putProperty("Ignore-Charset", "true" ) 没有区别。

【问题讨论】:

    标签: java html swing jeditorpane


    【解决方案1】:

    在 setText 之前和 setContentType 之后使用后续行。

    editor.getDocument().putProperty("IgnoreCharsetDirective", Boolean.TRUE);
    

    这是神秘的未记录功能之一。 setContentType 创建一个新的 Document ,如果你之前设置它没有效果。

    【讨论】:

    • 有趣,但是虽然此修复程序在运行时有效,但如果 HTML 代码中有字符集指令,Eclipse WindowBuilder 仍然无法呈现页面。
    【解决方案2】:

    当我运行代码时,我只能在删除 meta 行时看到 HTML 文本。可能跟运行系统的字符设置有关。

    【讨论】:

      猜你喜欢
      • 2011-05-07
      • 2019-06-01
      • 2013-04-14
      • 2011-06-06
      • 2011-11-18
      • 2012-07-29
      • 1970-01-01
      • 2012-06-11
      • 2012-01-02
      相关资源
      最近更新 更多