1

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?

4
  • Perhaps end the body tag before the <code> tags, then restate the body tag afterwards? Example: "Could not read the file </body><code> none.txt</code><body> Commented Dec 14, 2016 at 13:46
  • @joey942, I don't see the sense in it. Why excluding <code>none.txt</code> from <body> should work, and how can we have more than one <body>? anyway, tried that, it completely ignores the whole content of <p>, and all I see is the "Error:" text. Commented Dec 14, 2016 at 13:56
  • Then perhaps do this: <div id="notbody"><code>none.txt</code></div> Then in CSS, #notbody{ // set font size to what you want it to be} These are just suggestions, I have not tried them out myself. Commented Dec 14, 2016 at 14:01
  • I may have found something for you, this may help: stackoverflow.com/questions/16201948/… It has information on the not selector. Commented Dec 14, 2016 at 14:08

1 Answer 1

3

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>");
Sign up to request clarification or add additional context in comments.

2 Comments

That's annoying. Now I have to add inherit for every kind of block I may ever use? bold, code, etc... ?
I don’t think <b> needs it. Probably just the ones which change the font family. <code>, <pre>, <samp>, and possibly <kbd>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.