Smart String truncate

K

Katie

Hi,

I am trying to write a truncate method which will be able to
concatenate a String based on pixel width of the string rather than
the number of characters. I was trying to use the Fontmetrics object
but unfortunately its abstract and get be used with the Graphics
(abstract) object which i don't have.
Is there any way to accomplish this without using the Graphics object,
to use the Font class to set the font styles and then passing the
string and getting its width based on the Font and styles ?

Thanks for your help
:)
 
T

Tom Hawtin

Katie said:
I am trying to write a truncate method which will be able to
concatenate a String based on pixel width of the string rather than
the number of characters. I was trying to use the Fontmetrics object
but unfortunately its abstract and get be used with the Graphics
(abstract) object which i don't have.
Is there any way to accomplish this without using the Graphics object,
to use the Font class to set the font styles and then passing the
string and getting its width based on the Font and styles ?

java.awt.Font only contains information about font name, size, and
various other attributes. In order to get the FontMetrics for it, you
need to know how to acquire the font glyphs, how it's going to be
rendered (anti-aliasing implementations, for instance, often makes text
wider). How many pixels in 12pt Times Roman for the string "xyz"? Well,
it depends...

So, you need some context for this extra information. That is usually
what AWT provides through Graphics. Otherwise, you are left with
implementing FontMetrics yourself.

Tom Hawtin
 
D

Daniel Pitts

Hi,

I am trying to write a truncate method which will be able to
concatenate a String based on pixel width of the string rather than
the number of characters. I was trying to use the Fontmetrics object
but unfortunately its abstract and get be used with the Graphics
(abstract) object which i don't have.
Is there any way to accomplish this without using the Graphics object,
to use the Font class to set the font styles and then passing the
string and getting its width based on the Font and styles ?

Thanks for your help
:)

The number of pixels is based on how its going to be rendered.
Generally, you should truncate the text in the paintComponent method,
(where you actually have a Graphics object) rather than anywhere else.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top