How can I clip strings in Java2D and add ... in the end?
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 开发者_StackOverflowend 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
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.
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.
- Wikipedia - Binary Search Algorithm
String cutString(String originalString, int placeholderWidth, FontMetrics fontMetrics) {
int stringWidth = fontMetrics.stringWidth(originalString);
String resultString = originalString;
while (stringWidth >= placeholderWidth) {
resultString = resultString.substring(0, resultString.length() - 4);
resultString = resultString.concat("...");
stringWidth = fontMetrics.stringWidth(resultString);
}
return resultString;
}
精彩评论