Reputation: 69339
To customise the text displayed in a JComboBox
for arbitrary objects I know the correct approach is to create a custom ListCellRenderer
. However, I'm unsure how to do this in a way that mimics the same look and feel as a normal combo box.
Consider the SSCCE below. It works, but it has one unpleasant line in which I cast a component to a JLabel
. This is a piece of magic knowledge I shouldn't have nor should rely upon. Is there any other way to get the same effect without doing something so ugly?
public class ListCellRendererExample {
private final JFrame frame;
public ListCellRendererExample() {
frame = new JFrame();
JComboBox<SomeObject> combobox = new JComboBox<>(
new SomeObject[] { new SomeObject("a") });
ListCellRenderer<? super SomeObject> cellRenderer = combobox.getRenderer();
combobox.setRenderer(new CustomRenderer(cellRenderer));
frame.add(combobox);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new ListCellRendererExample();
}
private class CustomRenderer implements ListCellRenderer<SomeObject> {
private final ListCellRenderer<? super SomeObject> defaultRenderer;
public CustomRenderer(ListCellRenderer<? super SomeObject> cellRenderer) {
this.defaultRenderer = cellRenderer;
}
@Override
public Component getListCellRendererComponent(
JList<? extends SomeObject> list, SomeObject value, int index,
boolean isSelected, boolean cellHasFocus) {
Component result = defaultRenderer.getListCellRendererComponent(list,
value, index, isSelected, cellHasFocus);
((JLabel) result).setText(value.value); // <--- URGH!
return result;
}
}
private static class SomeObject {
private final String value;
public SomeObject(String nombre) {
this.value = nombre;
}
}
}
Upvotes: 1
Views: 2628