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

Graphics-how to tell width of a string

Posted on 2001-06-12
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
  • 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 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 :-)

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
ejb on wildfly 5 30
maven disable workspace resolution 1 21
add projects t working set in maven 2 22
Java basic valueOf question 1 29
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
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…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

856 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