Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8214429

Preferred width of a Component is incorrect when using a custom Font

XMLWordPrintable

    • 2d
    • 11
    • x86_64
    • windows_10

      ADDITIONAL SYSTEM INFORMATION :
      Java 11 on any system/OS.

      A DESCRIPTION OF THE PROBLEM :
      A regression related to FontMetrics was introduced in Java 11 when a custom Font is set on a Component. This causes the Component to size itself incorrectly leading to cut off text. This problem does not exist in Java 8.

      REGRESSION : Last worked in version 8u181

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      A test program is provided below. Run on Java 11 and run on Java 8 to see the difference. If you actually render the label, the text will be cut off in Java 11 as the preferred size of the component is computed incorrectly.


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Run the test program on Java 8, the preferred size is correctly shown as 44.

      String bounds: java.awt.geom.Rectangle2D$Float[x=0.0,y=-9.004395,w=44.0,h=10.863281]
      Preferred size: java.awt.Dimension[width=44,height=11]

      ACTUAL -
      Run the test program on Java 11, the preferred size is incorrectly shown as 40.

      String bounds: java.awt.geom.Rectangle2D$Float[x=0.0,y=-9.004395,w=44.0,h=10.863281]
      Preferred size: java.awt.Dimension[width=40,height=11]


      ---------- BEGIN SOURCE ----------
      import javax.swing.*;
      import java.awt.

      public class Test {
        public static void main(final String args[]) {
              String str = "Used: N/A";
              JLabel label = new JLabel(str);
              label.setFont(new Font("Tahoma", Font.PLAIN, 9));

              System.err.println("String bounds: " + label.getFontMetrics(label.getFont()).getStringBounds(str, label.getGraphics()));
              System.err.println("Preferred size: " + label.getPreferredSize());
          }
      }

      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      You could override getPreferredSize() on all components that might have a Font set on them, e.g. JLabel, JButton, etc. This isn't really a workable solution. We have encountered this in 3rd party libraries for which we cannot change the behavior.

      FREQUENCY : always


            prr Philip Race
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: