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.
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.
I personally was searching for something to let me compute the multiline string area, so I could determine if given area is big enough to print the string - with preserving specific font.
I hope it would safe some time to another guy who may want to do similar job in java so just wanted to share the solution:
Use the getWidth method in the following class:
It doesn't always need to be toolkit-dependent or one doesn't always need use the FontMetrics approach since it requires one to first obtain a graphics object which is absent in a web container or in a headless enviroment.
I have tested this in a web servlet and it does calculate the text width.
Add the necessary values to these dimensions to create any required margin.
If you just want to use AWT, then use
Graphics.getFontMetrics
(optionally specifying the font, for a non-default one) to get aFontMetrics
and thenFontMetrics.stringWidth
to find the width for the specified string.For example, if you have a
Graphics
variable calledg
, you'd use:For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.