views:

5115

answers:

3

How to calculate the length (in pixels) of a string in Java?

Preferable without using Swing.

EDIT: I would like to draw the string using the drawString() in Java2D and use the length for word wrapping.

+4  A: 

How are you going to draw the string? With AWT? Or with some other toolkit? The size of the string in pixels depends on the drawing API that will draw the pixel later on (and of course which font you use and what font size and if the font is bold/italic, etc.). W/o knowing the drawing API and the font properties, a string has no size whatsoever.

Mecki
+14  A: 

If you just want to use AWT, then use Graphics.getFontMetrics (optionally specifying the font, for a non-default one) to get a FontMetrics and then FontMetrics.stringWidth to find the width for the specified string.

For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.

Jon Skeet
A: 

When I try to use FontMetrics for this purpose in WSAD (WebSphere Studio Application Developer), I get the error "The type FontMetrics cannot be instantiated" when compiling. Is there a way to fix it? I am using this for an excel api to calculate how wide the string is displayed so I can figure out what to set the column width to.