Link to home
Start Free TrialLog in
Avatar of tom_corc
tom_corc

asked on

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?
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

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
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" ) ;
}
ASKER CERTIFIED SOLUTION
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial