I am using JTextPane as a table cell renderer to display rich text. When the text is too long to fit inside a cell, it is truncated. I would like to mimic the JLabel behavior, i.e. show ellipsis (…) to alert the user that part of the text is not visible. Has anyone done this before?
Solution I ended up adopting, with help from StanislavL. The algorithm works by chopping off one character at a time off the end of StyledDocument, appending “…” and comparing resulting preferred width to table cell width. This is inefficient, especially in case of very long strings, but not a problem in my case. Can be optimized. The following goes into your renderer’s getTableCellRendererComponent
m_dummyTextPane.setDocument(doc);
m_dummyTextPane.setSize(Short.MAX_VALUE, table.getRowHeight());
int width = m_dummyTextPane.getPreferredSize().width;
int start = doc.getLength() - 1;
while(width >= table.getColumnModel().getColumn(col).getWidth() && start>0) {
try {
doc.remove(Math.min(start, doc.getLength()),
doc.getLength() - Math.min(start, doc.getLength()));
doc.insertString(start, "...", null);
} catch (BadLocationException e) {
e.printStackTrace();
break;
}
start--;
width = m_dummyTextPane.getPreferredSize().width;
}
You can use this http://java-sl.com/tip_text_height_measuring.html to measure content for the fixed width. If it requires more space than available just paint something over the JTextPane.
I like the trashgod’s idea with scroll too. (+1)