JCombobox in Java 7 has been updated to use generics - I always thought it was a bit of an oversight that it didn't already so I was pleased to see this change.
However, when attempting to use JCombobox in this way, I realised that the methods I expected to use these generic types still just return Object.
Why on earth is this? It seems like a silly design decision to me. I realise the underlying ListModel has a generic getElementAt()
method so I'll use that instead - but it's a bit of a roundabout way of doing something that appears like it could have been changed on JComboBox itself.
I suppose you refer to getSelectedItem()
?
The reason is that if the combo box is editable, the selected item is not necessarily contained in the backing model and not constrained to the generic type. E.g. if you have an editable JComboBox<Integer>
with the model [1, 2, 3], you can still type "foo" in the component and getSelectedItem()
will return the String "foo" and not an object of type Integer.
If the combo box is not editable, you can always defer to cb.getItemAt(cb.getSelectedIndex())
to achieve type safety. If nothing is selected this will return null
, which is the same behaviour as getSelectedItem()
.