Gioce90
Gioce90

Reputation: 623

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?

Upvotes: 0

Views: 259

Answers (3)

user4140813
user4140813

Reputation: 11

When filling the comboBox, by default, the toString() method of all elements is called. The toString() method of Class returns the full class Name as explained here. In the getSelectedItem() method, you call getSimpleName() which of course returns the simple name of the class.

To solve your Problem, you need to create a custom list cell renderer, and overwrite getListCellRendererComponent.

Upvotes: 1

ug_
ug_

Reputation: 11440

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.

Upvotes: 1

Stefan
Stefan

Reputation: 12453

You need to create a custom ListCellRenderer.

Upvotes: 0

Related Questions