Question

I want to write a custom ListCellRenderer.

Only thing that needs to be different from the default one is that it doesn't display the return value of value.toString(), but eturn value of value.myOwnCustomMethodThatReturnsString().

What is the simplest way of doing that?

The class all this is in already implements ListCellRenderer and I have:

public Component getListCellRendererComponent(JList<? extends Chapter> list,
        Chapter value, int index, boolean isSelected, boolean cellHasFocus)
{
    return null;
}

I just don't know what to put inbetween the brackets...

Was it helpful?

Solution

The simplest way is:

public class MyRenderer extends DefaultListCellRenderer {

    @Override
    public Component getListCellRendererComponent(JList<? extends Chapter> list, Chapter value, int index, boolean isSelected, boolean cellHasFocus)
    {
       Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

       if (c instanceof Jlabel) { // it would work because DefaultListCellRenderer usually returns instance of JLabel
           ((JLabel)c).setText(value.myOwnCustomMethodThatReturnsString()); 
       }

       return c;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top