Search code examples
javaswingjlabeljlistlistcellrenderer

ListCellRenderer - JLabel - String - n rows


So I have this situation:

I have a JList that displays a bunch of Strings.

However, these strings are really long and JList is really narrow. Meaning the strings won't fit.

What I want to do is make each entry to have two rows, like this:

|Word word word  |
|word word wor...|

It would do wordWrap for the first row, and then finish the secon't row by cutting the rest of the string and appeinging the three dots to what is left in a way maximum space is filled.

It doesn't really matter what I do, the important thing is that I have to use FontMetrics to measure all this stuff so I can make it work. And that's the catch.

Until whole getListCellRendererComponent(...) method is executed, the component will not be painted, thus having no graphics, thus making any font measurement impossible.

How do I get around it?

P.S. I need to use the JLabel for the visuals.


Solution

  • the component will not be painted, thus having no graphics, thus making any font measurement impossible.

    You don't need the Graphics to use the FontMetrics.

    See Left Dot Renderer which is used for a JTable, but the concepts should be the same for a list renderer as well.