Reputation: 623
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:
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
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
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