java - JEdi​​torPane 在显示 HTML 时是否有 Charset 问题?

标签 java html swing jeditorpane

我有以下代码:

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 字符串......)。

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

最佳答案

在 setText 之前和 setContentType 之后使用以下行。

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

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

关于java - JEdi​​torPane 在显示 HTML 时是否有 Charset 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/178667/

相关文章:

html - 在 html 中放置 facebook、twitter 和 Google+ 共享按钮的最佳方式?

java - 2D游戏中的碰撞

java - 带有预装插件的 Eclipse

java - Spring boot - 使用 Logback 发送电子邮件

javascript - 如何使单选按钮组可折叠?

更新频繁的 Java JTable?

java - 当试图移动到底部时,JPanel 被压缩并消失

JavaScript 执行器在 Google Chrome 中工作,但在 Firefox 中不起作用

java - 树集未添加所有对象

javascript - 媒体查询打印不适用于 javascript 命令