Duncan Jones
Duncan Jones

Reputation: 69339

Create a ListCellRenderer that looks like the default?

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

Answers (1)

Mark
Mark

Reputation: 29119

If you want to avoid the cast why not have your custom ListCellRenderer extend JLabel in the same way the DefaultListCellRenderer does.

See the example here.

Upvotes: 1

Related Questions