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

时间:2016-12-14 13:42:42

标签: java html swing jtextpane

我有这段代码来显示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);

但这是输出:

enter image description here

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

绝对是一个错误。您可以通过在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>");