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

getStringBounds not returning complete string bounds

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Unresolved
    • Icon: P4 P4
    • None
    • 1.2.0, 1.4.0
    • client-libs
    • 2d
    • generic, x86
    • generic, windows_98, windows_nt

      FontMetrics.getStringBounds does not seem to be returning the complete bounds of a String with certain fonts and String combinations. The following code draws a String via drawString, and then draws a rectangle with the return value from getStringBounds. As you can see, the text extends beyond the bounds of the rectangle with certain strings and fonts. This happens on Merlin build 28 on both Windows and Solaris.

      import java.awt.*;
      import java.awt.font.*;
      import java.awt.geom.*;

      public class FontTest extends Component {
          public static void main(String[] args) {
              Frame f = new Frame();

              f.setLayout(new BorderLayout());
              f.add(new FontTest(), BorderLayout.CENTER);
              f.pack();
              f.show();
          }

          public Dimension getPreferredSize() {
              return new Dimension(400, 600);
          }

          public void paint(Graphics g) {
              g.setColor(Color.white);
              g.fillRect(0, 0, getWidth(), getHeight());

              // From bug 4262130
              String text = "Hellow, WorldN";
              Font font = new Font("Serif",Font.BOLD + Font.ITALIC, 24);

              g.setFont(font);

              paintUsingGetStringBounds(g, text, 70);

              // From bug 4140220
              font = new Font("SansSerif", Font.PLAIN, 11);
              text = "W";

              g.setFont(font);
              paintUsingGetStringBounds(g, text, 220);
          }

          // Parry suggest using FontMetrics.getStringBounds to account for the
          // lead in characters such as W
          private void paintUsingGetStringBounds(Graphics g, String text, int y) {
              FontMetrics fm = g.getFontMetrics(g.getFont());
              Rectangle2D rect = fm.getStringBounds(text, g);

              g.setColor(Color.black);
              g.drawString(text, 10, y - (int)rect.getY());
              g.setColor(Color.red);
              g.drawRect(10 + (int)rect.getX(), y, (int)rect.getWidth() + 1,
                         (int)fm.getHeight());
              System.out.println(text + " getStringBounds = " + rect);
          }
      }

            dougfelt Doug Felt (Inactive)
            svioletsunw Scott Violet (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Imported:
              Indexed: