Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the display width of a string in Java

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.

like image 476
eflles Avatar asked Nov 03 '08 12:11

eflles


1 Answers

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.

like image 141
Jon Skeet Avatar answered Sep 24 '22 14:09

Jon Skeet