Obtaining the size of the string in java (without having a graphical object available)

advertisements

I'm trying to write application which need to draw many strings using Graphics2D class in Java. I need to get sizes of each String object (to calculate exact position of each string). There is so many strings that it should be done before the paint() method is called and only once at the beginning of my program (so then I don't have Graphics2D object yet). I know that there is a method Font.getStringBounds() but it needs a FontRenderContext object as a parameter.

When i tried to create my own object:

FontRenderContext frc = new FontRenderContext(MyFont.getTransform(), true, true)

and then obtain the strings bounds I've always get different sizes than when I obtain FontRenderContext using Graphics2D.getFontRenderContext() method inside paint() method. The differences are not big (about 1E-3) but I wonder why there is any difference?

However, is there any better and secure way to obtain sizes of a string?

Thnx for any help in advance!


Try with the FontMetrics class; the stringWidth method returns the size of a string. An example:

JComponent c = getSomeKindOfJComponent();
FontMetrics fm = c.getFontMetrics(c.getFont()); // or another font
int strw = fm.stringWidth("My text");