Why isn't getSelectedItem() on JComboBox generic?

JavaSwingGenericsJcomboboxJava 7

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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().

Solution 2 - Java

Here is a type-safe version:

public static <T> T getSelectedItem(JComboBox<T> comboBox)
{
	int index = comboBox.getSelectedIndex();
	return comboBox.getItemAt(index);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael BerryView Question on Stackoverflow
Solution 1 - JavajarnbjoView Answer on Stackoverflow
Solution 2 - JavaBullyWiiPlazaView Answer on Stackoverflow