Graphics-how to tell width of a string

Posted on 2001-06-12
Medium Priority
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?
Question by:tom_corc
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
LVL 35

Expert Comment

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!!

LVL 35

Expert Comment

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" ) ;
LVL 35

Accepted Solution

TimYates earned 400 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 :-)

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
This video teaches viewers about errors in exception handling.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month12 days, 4 hours left to enroll

752 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