I render text with a custom table cell renderer and I want to trim the text drawn if it would exceed the current cell width, switching to a "This text is to long..." kind of representation, where the three dots at the end never leaves the bounding box. My current algorithm is the following:
FontMetrics fm0 = g2.getFontMetrics();
int h = fm0.getHeight();
int ellw = fm0.stringWidth("\u2026");
int titleWidth = fm0.stringWidth(se.title);
if (titleWidth > getWidth()) {
for (int i = se.title.length() - 1; i > 0; i--) {
String tstr = se.title.substring(0, i);
int tstrw = fm0.stringWidth(tstr);
if (tstrw + ellw < getWidth()) {
g2.drawString(tstr, 2, h);
g2.drawString("\u2026", 2 + tstrw, h);
break;
}
}
} else {
g2.drawString(se.title, 2, h);
}
Is there a better way of determining how many characters should I drawString()
before switching to the ... (u2026) character?