Graphics-how to tell width of a string

I want to tell how wide a string (say "abcde") would be in pixels using a particular font.
Is it possible to do this?
tom_corcAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
TimYatesConnect With a Mentor Commented:
You can also call getFontMetrics() from any component (Frame, JFrame, JPanel, etc) if you are writing an app...

Good Luck again!!

Three post Tim :-)
0
 
TimYatesCommented:
public void paint( Graphics p )
{
  Font f = new Font( "Helvetica", Font.BOLD, 12 ) ;
  g.setFont( f ) ;
  FontMetrics fm = getFontMetrics( f ) ;
  int width = fm.stringWidth( "abcde" ) ;
}

should do it...(for an applet)

Good Luck!!

Tim
0
 
TimYatesCommented:
Obviously, if you havent set a font, then you can do:

public void paint( Graphics p )
{
 FontMetrics fm = getFontMetrics( getFont() ) ;
 int width = fm.stringWidth( "abcde" ) ;
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.