Why isn't getSelectedItem() on JComboBox generic?

余生长醉 提交于 2019-12-18 12:44:59

问题


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.


回答1:


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




回答2:


Here is a type-safe version:

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


来源:https://stackoverflow.com/questions/7026230/why-isnt-getselecteditem-on-jcombobox-generic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!