JTextPane,text/html 内容:嵌套的HTML 元素不继承字体大小?

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

我有这段代码可以显示 HTML 格式的字符串:

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);

但这是输出:

您可以看到 none.txt 字符串没有继承其封闭段落的字体大小,尽管这是 HTML (see jsfiddle) 中应该发生的情况。

我该如何解决这个问题?

绝对是一个错误。您可以通过在 CSS 中使用 <style> 元素添加显式继承来解决此问题:

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>");