Java – Does JEditorPane have Charset problems when showing HTML


I have the following code:

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>"+
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"/>"+ // this is the problem right here
"<title>Error 400 BAD_REQUEST</title>"+
"<h2>HTTP ERROR: 400</h2><pre>BAD_REQUEST</pre>"+
"<p><i><small><a href=\"\">Powered by jetty://</a></small></i></p>"+
        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.setVisible( true );


If you run it, you'll notice the frame is blank. However, if I remove the "; charset=ISO-8859-1" from the meta tag, the HTML shows up. Any ideas why and what I can do to prevent this (other than manually hacking the HTML string over which I have no control…).

Edit #1 – putProperty( "Ignore-Charset", "true" ) makes no difference unfortunately.

Best Solution

Use the follow line before setText and after setContentType.

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

This is one of the mystic undocumented features. setContentType create a new Document that it has no effect if you set it before.