Here's a utility interface and class that make it easy to get a combo box to use different labels. Instead of creating a replacement ListCellRenderer
(and risking it looking out of place if the look-and-feel is changed), this uses the default ListCellRenderer
(whatever that may be), but swapping in your own strings as label text instead of the ones defined by toString()
in your value objects.
public interface ToString {
public String toString(Object object);
}
public final class ToStringListCellRenderer implements ListCellRenderer {
private final ListCellRenderer originalRenderer;
private final ToString toString;
public ToStringListCellRenderer(final ListCellRenderer originalRenderer,
final ToString toString) {
this.originalRenderer = originalRenderer;
this.toString = toString;
}
public Component getListCellRendererComponent(final JList list,
final Object value, final int index, final boolean isSelected,
final boolean cellHasFocus) {
return originalRenderer.getListCellRendererComponent(list,
toString.toString(value), index, isSelected, cellHasFocus);
}
}
As you can see the ToStringListCellRenderer
gets a custom string from the ToString
implementation, and then passes it to the original ListCellRenderer
instead of passing in the value object itself.
To use this code, do something like the following:
// Create your combo box as normal, passing in the array of values.
final JComboBox combo = new JComboBox(values);
final ToString toString = new ToString() {
public String toString(final Object object) {
final YourValue value = (YourValue) object;
// Of course you'd make your own label text below.
return "custom label text " + value.toString();
}
};
combo.setRenderer(new ToStringListCellRenderer(
combo.getRenderer(), toString)));
As well as using this to make custom labels, if you make a ToString
implementation that creates strings based on the system Locale, you can easily internationalize the combo box without having to change anything in your value objects.