views:

36

answers:

2

I'm trying to print Invoices in a Java Swing applications. I do that by extending Printable and implement the method public int print(Graphics g, PageFormat pf, int page).

I would like to draw strings in columns, and when the string is to long I want to clip it and let it end with "...". How can I measure the string and clip it at the right position?

Some of my code:

Font headline = new Font("Times New Roman", Font.BOLD, 14);
g2d.setFont(headline);
FontMetrics metrics = g2d.getFontMetrics(headline);
g2d.drawString(myString, 0, 20);

I.e How can I limit myString to be max 120px?

I could use metrics.stringWidth(myString), but I don't get the position where I have to clip the string.

Expected results could be:

A longer string that exc...
A shorter string.
Another long string, but OK
A: 

Once you know that the string needs to be clipped, you can use a binary search to see how many characters you can display, including the elipsis suffix.

This is similar to if you were to try N-1 chars, N-2, N-3 etc.. until you found a substring + "..." that fits within the allowed space. But rather than iterate linearly, you use binary search to find the number of characters with fewer attempts.

mdma
A: 

You can get a good estimate by taking the stringWidth divided by the number of characters to get the average width per character. Then you can take the clip distance to see how many characters you can fit in. Take the substring from the start to almost that distance (minus two or three for the ...) and put your ... on the end.

Verify the new string doesn't clip - if it does, make some adjustments as necessary. After all if you have WWWWWWWWiiiiii, you'll probably need to adjust that. But all in all, this approach will be pretty fast.

glowcoder