FOLLOW ME Twitter Facebook Вконтакте LinkedIn RSS Feed

Bug with stringWidth() in JDK 1.7.0_40

Category: Java
Sep 13, 2013
Konstantin Bulenkov

Today I found that JDK 1.7.0_40 has a bug in the strings width calculation for some fonts. The problem easily reproduces with Retina displays. I wrote a test to do this:

import javax.swing.*;
import java.awt.*;

 * @author Konstantin Bulenkov
public class TextWidthTest extends JFrame {
  public TextWidthTest() throws HeadlessException {
    super("Text Width Test in JDK 1.7.0_40");
    setSize(280, 40);
    final String str = "nnnnnnnnnnnnnnnnnnnn.txt";
    JComponent customComp = new JComponent() {
      protected void paintComponent(Graphics g) {
        FontMetrics fm = getFontMetrics(getFont());
        g.fillRect(0, 0, fm.stringWidth(str), fm.getHeight());
        g.drawString(str, 0, fm.getHeight());
    Font font = new Font("Lucida Grande", Font.PLAIN, 12);

  public static void main(String[] args) {
    new TextWidthTest();

I was playing with the test and found out that FontMetrics returns a wrong width for some combinations of symbols and fonts. I decided to have a break after this:



  • It looks like it has something to font sizes. For instance, Menlo 13 works OK, but Menlo 12 reports wrong sizes

    • Same with Lucida Grande 12 and others. stringWidth() works just fine for 13ep. I’ve sent this to the 2d-dev mailing list

  • I’ve been getting the same problem (in 1.7.0_51). Interestingly though, the font metrics only seem to be wrong if you invoke java via the command line. If you use AppBundlerTask then the resulting app seems to use the correct font metrics.

    • Please strike my previous comment, I wasn’t looking closely enough. When running my bundled app the Info.plist didn’t correct specify Retina display support. So, the problem occurs whenever you use Retina support, regardless of how the app is invoked.

Leave a comment