0

I used fontmetrics to determine the length and height of the String drawn to a jpanel but it gave me incorrect measurements.

The String I used was: "Hello World this is fantastic"

For example: a drew a string with the default font; according to the font metrics the dimensions were: height: 24; width: 224.

when I measured it, it was in fact 148 pixels long and 10 pixels in height. (basically by trial and error)

FontMetrics fm = g.getFontMetrics(this.f);
int Ilength = fm.stringWidth("Hello World this is fantastic");
int Iheight = fm.getHeight();
System.out.println("height: " + Iheight + "; width: " + Ilength);

I am wondering if there is a formula or method in java that can provide the actual height and width of the string in pixels. Thanks!

nathannn
  • 1
  • 1
  • 1

1 Answers1

0

I also had this problem. Try to use the method getStringBounds(String,Graphics) of your FontMetrics object.

public Rectangle2D bounds = fm.getStringBounds("Hello World this is fantastic", g);
int Ilength = (int)bounds.getWidth();
int Iheight = (int)bounds.getHeight();
Alex
  • 1
  • 2