2

I want to get the exact height of my string in pixels on my panel. So I wrote a program that draws the string, and then draws a rectangle around it.

Using FontMetrics I used the getStringBounds method to get me the enclosing rectangle.

However it looks wrong :

enter image description here

I was expecting the rectangle to perfectly enclose my text, but there is space at the top (And a tiny bit of space on the left and right). Why is it giving me this result?

Here is my code :

public class Test extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {

        Font font = new Font("Arial", Font.PLAIN, 60);
        g.setFont(font);

        FontMetrics fm = this.getFontMetrics(font);

        String str = "100dhgt";
        Rectangle2D rect = fm.getStringBounds(str, g);

        int x = 5;
        int y = 100; 

        g.drawRect(x, y - (int)rect.getHeight(), (int)rect.getWidth(), (int)rect.getHeight());
        g.drawString(str, x, y);
    }

    public static void main(String[] args) {
        JFrame f = new JFrame();

        Test test = new Test();
        f.add(test);
        f.setVisible(true);
        f.setSize(400, 400);
    }

}
Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225

2 Answers2

5

Regarding your rectangle, you have to consider the font's descend (how far is it below the line)

g.drawString(str, x, y - fm.getDescent());

Also note that the font height usually considers some kind of line spacing. In this case fm.getDescent() + fm.getAscent() = 68 whereas fm.getHeight() = 70

mtj
  • 3,381
  • 19
  • 30
2

The space at the top can be explained by your not taking account of the descent (which takes me back to one of my favorite methods from java 1.0: getMaxDecent)

Otherwise, the box looks pretty good. The only other advice I can offer is that fm.getStringBounds works better with some fonts than it does with others

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80