Search code examples
javahtmlswingjtextpane

JTextPane, text/html content: nested HTML element do not inherit font size?


I have this code to display HTML formatted string:

JTextPane pane = new JTextPane();
        pane.setContentType("text/html");
        pane.setEditable(false);
        pane.setText(
            "<html>" +
                "<body style='font-size:18px'>" +
                    "<h1>Error:</h1>" +
                    "<p>" +
                        "Could not read the file <code>none.txt</code>. " +
                        "Perhaps it does not exist in the specified location, " +
                        "or possibly there is no access to it" +
                    "</p>" +
                "</body>" +
            "</html>");
        add(pane);

But this is the output:

enter image description here

You can see that the none.txt string doesn't inherit the font size of its enclosing paragraph, although this is what's supposed to happen in HTML (see jsfiddle).

How do I fix this?


Solution

  • Definitely a bug. You can work around it by adding explicit inheritance in the CSS, with a <style> element:

    pane.setText(
        "<html>" +
            "<style>\ncode { font-size: inherit; }\n</style>" +
            "<body style='font-size:18px'>" +
                "<h1>Error:</h1>" +
                "<p>" +
                    "Could not read the file <code>none.txt</code>. " +
                    "Perhaps it does not exist in the specified location, " +
                    "or possibly there is no access to it" +
                "</p>" +
            "</body>" +
        "</html>");