Getting string size in java (without having a Graphics object available)

Lukasz Spas picture Lukasz Spas · Feb 6, 2011 · Viewed 14.4k times · Source

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 are 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(). The differences are not big (about 1E-3) but I wonder why there is any difference at all?

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

Thnx for any help in advance!

Answer

Alberto picture Alberto · Feb 6, 2011

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");