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.
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 example, if you have a Graphics
variable called g
, you'd use:
int width = g.getFontMetrics().stringWidth(text);
For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.