3

I ran into an issue with specifying a html element's width in a JLabel and thought I would run it up the flag pole here and see if anyone had any advice.

When I specify the width of an element using a "px" unit value, the resulting size is actually ~133%, whereas if I don't use a unit, or use "pt", I get the exact size I specified.

In the below example, if you change the "width: 100px" to "width: 100pt", you will get the right size.

This answer https://stackoverflow.com/a/6257861/131795 seems to be related, and the 72 dpi adjustment seems to match with the mismatch that I'm seeing in in my example.

I might be raging against an ancient piece of code here, but why is an absolute px value being converted and a pt value being treated as absolute?

public class test {
    public static void main(String args[]) {
        JFrame frame = new JFrame();

        JLabel label = new JLabel("<html><div style='width: 100px; background-color: red;'>test</div>");
        frame.getContentPane().add(label);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 200);
        frame.setVisible(true);
    }
}
VGR
  • 40,506
  • 4
  • 48
  • 63
Trevor Harrison
  • 1,744
  • 1
  • 14
  • 20

1 Answers1

2

Ok, I think I've found the 'reason' (or culprit) for java scaling pixel values.

In the HTMLEditorKit implementation, there is a CSS class that handles css stuff. It has a table with scaling values for each supported unit. (starting on line 2843 in CSS.class)

For "pt", it is 1-to-1 mapping. For "px", its 1-to-1.3 mapping. There is even a comment that says:

// Not sure about 1.3, determined by experiementation.

There are actually two mapping tables, where the second one is used if the w3c mode is turned on. It has scaling modes that are backwards from the first table:

For "pt", it is 1-to-screenres/72dpi. For "px", its 1-to-1 mapping.

I'm not sure what activates the w3c mode, but beware of the issue.

Trevor Harrison
  • 1,744
  • 1
  • 14
  • 20
  • 1
    w3c mdoe is enabled by ``W3C_LENGTH_UNITS`` https://docs.oracle.com/javase/7/docs/api/javax/swing/JEditorPane.html#W3C_LENGTH_UNITS – user996142 Oct 08 '20 at 13:39
  • 1
    If anyone ever comes here again (probably myself): It's also possible to activate the W3C table by adding a "rule" to the root stylesheet of the `HTMLDocument` which contains exactly the string `"W3C_LENGTH_UNITS_ENABLE"`: `document.styleSheet.addRule("W3C_LENGTH_UNITS_ENABLE");` – manu_unter Jul 28 '22 at 17:55