How can I clip strings in Java2D and add ... in the end?

Posted by Jonas on Stack Overflow See other posts from Stack Overflow or by Jonas
Published on 2010-05-17T13:22:19Z Indexed on 2010/05/17 14:50 UTC
Read the original article Hit count: 284

Filed under:
|
|
|
|

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

© Stack Overflow or respective owner

Related posts about java

Related posts about swing