Drawing a max length str...

I’m trying to find a way to draw a string so that is ends abruptly with “…” without much hassle.

So, let’s imagine we have the string “Today is a sunny day.” But we can only draw in a area of width 100 pixels, so because of that limit only “Today is a su…” is drawn.

So, what’s the most right way to do this? :slight_smile:

Assuming Java2D?

Use FontMetrics to get the string bounds, and keep trying with a smaller String.

Or, have a look at the HtmlRenderer (GPL w/CPE or CDDL) class from NetBeans, which does this for plain Strings too.
Code - http://www.java2s.com/Open-Source/Java-Document/IDE-Netbeans/openide/org/openide/awt/HtmlRenderer.java.htm
JavaDoc - http://bits.netbeans.org/dev/javadoc/org-openide-awt/org/openide/awt/HtmlRenderer.html

NB. Not sure how old that code link is. Could also look in the NetBeans repo.

Best wishes, Neil

Yea, Java2d. I am currently using FontMetric, and just brute-force checking how many characters I can render.

I was hoping there was something more automatic way of doing it, like:
StringDrawer.draw(“Today is a sunny day.”, 100, “…”);

Looks like I’ll have to day it using FontMetric.

Well, you’ll have to code it yourself. You can check the width of individual chars. The total string width should be the sum of all character in the string, there is no such guarantee if you check the FontMetrics Javadoc. Just brute force it, shouldn’t be that slow unless you’re doing it a lot, and cache the result. I mean, if you’re doing window titles or something, only recalculate this when the window changes.

Well, that NetBeans class ain’t far off that! :slight_smile:

Although it’s only doing the brute force thing for you. I assume you’ve noticed that FontMetrics can work with char[] as well as String so you don’t need to keep creating objects - just ask because I hadn’t until I saw the HtmlRenderer code.