Pixel length of string

Hey,

I am programming a multiplayer game with a lobby system. In the lobby I draw a picture that looks like a chatbox, and over it I draw a StringBuffer, using .append(char) to add letters as they are typed.

My problem is that if I type ‘WWWWWWWWWWWWWWWWW’ it may reach the edge of the box at say 15 chars, so I’d want it to be stopped. If I type ‘iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii’ it’ll be more like 25 chars, so I can’t limit it by length(). Seems a pretty simple problem, any ideas?

EDIT: Nevermind, literally just found it: SwingUtilities.computeStringWidth( fontMetrics, stringToComputeTheWidth );

Have a look at this site

http://www.javadocexamples.com/java/awt/FontMetrics/stringWidth(String%20str).html

you can use something like

FontMetrics fm = rendComp.getFontMetrics(rendComp.getFont());

int stringWide=fm.stringWidth(“WAWAWIii”);
int charWide=fm.charWidth(‘O’);

Note rendComp has to be of type java.awt.Graphics2D :slight_smile: