File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes calculate string width Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "calculate string width" Watch "calculate string width" New topic

calculate string width

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi all,
i have a quite strange requirement. I need to calculate the width of a String (fix length of 60 chars)with a given Font and Font size. I need this to calculate if all Strings match into one Table (fix size) on an HTML page.
Has anyone of you ever did this, or has an idea how to solve it ?
[ October 07, 2003: Message edited by: Oliver Refle ]
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
The FontMetrics class has several methods to help you with this.

int getMaxAdvance()
The advance width (in pixels) of the widest character in the font.
int bytesWidth(byte[], int, int)
The advance width of the text represented by the specified array of
bytes. The first integer argument specifies the starting offset of the
data within the byte array. The second integer argument specifies the
maximum number of bytes to check.
int charWidth(int), int charWidth(char)
The advance width of the specified character.
int charsWidth(char[], int, int)
The advance width of the string represented by the specified
character array.
int stringWidth(String)
The advance width of the specified string.
int[] getWidths()
The advance width of each of the first 256 characters in the font.

from Sun's Working with Text Tutorial

"JavaRanch, where the deer and the Certified play" - David O'Meara
I agree. Here's the link:
subject: calculate string width
It's not a secret anymore!