Solved

Graphics-how to tell width of a string

Posted on 2001-06-12
3
168 Views
Last Modified: 2010-03-31
I want to tell how wide a string (say "abcde") would be in pixels using a particular font.
Is it possible to do this?
0
Comment
Question by:tom_corc
  • 3
3 Comments
 
LVL 35

Expert Comment

by:TimYates
ID: 6180741
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
 
LVL 35

Expert Comment

by:TimYates
ID: 6180747
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
 
LVL 35

Accepted Solution

by:
TimYates earned 100 total points
ID: 6180752
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

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
The viewer will learn how to implement Singleton Design Pattern in Java.
This video teaches viewers about errors in exception handling.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question