Solved

Graphics-how to tell width of a string

Posted on 2001-06-12
3
164 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
Comment Utility
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
Comment Utility
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
Comment Utility
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

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…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

744 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now