javaclassuser-interfacejcomboboxcomboboxmodel

how use JComboBox with Class value


I have made this:

private JComboBox vehicleType = new JComboBox();
DefaultComboBoxModel<Class> dcbm = new DefaultComboBoxModel<Class>( 
        new Class[] {Truck.class, Trailer.class, RoadTractor.class, SemiTrailer.class, Van.class, Car.class})
{
    @Override
    public String getSelectedItem() {
        return ((Class<?>)super.getSelectedItem()).getSimpleName();
    }

};

And I have obtained this:

enter image description here

How you can see, the selected item show his simple class name, but in the list... doesn't. How I can make this?


Solution

  • JComboBox uses the toString() method to get the label, you can override the behavior by implementing a ListCellRenderer.

    vehicleType.setRenderer(new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if(value != null) {
                setText(((Class)value).getSimpleName());
            }
            return this;
        }
    });
    

    Also if you use this method you should remove the override of getSelectedItem() in your model as it will interfere with the renderer.