Why is getSelectedItem () not common to JComboBox?

JCombobox in Java 7 has been updated to use generics - I always thought it was a bit of an oversight, that it was not there yet, so I was pleased to see this change.

However, trying to use JCombobox in this way, I realized that the methods that I expected to use these generic types had just returned Object.

Why is this so? I think this is a stupid design decision. I understand that the underlying ListModel has a common getElementAt() method, so I will use it instead, but it's a bit of a roundabout way, something like it could be changed on the JComboBox itself.

+46
java generics java-7 swing jcombobox
Aug 11 '11 at 12:55
source share
2 answers

I assume you are referring to getSelectedItem() ?

The reason is that if the combo box is editable, the selected item is not necessarily contained in the backup model and is not limited to the general type. For example. if you have an editable JComboBox<Integer> with the model [1, 2, 3], you can still enter "foo" in the component, and getSelectedItem() will return the string "foo", not an object of type Integer.

If the combo box is not editable, you can always cb.getItemAt(cb.getSelectedIndex()) to cb.getItemAt(cb.getSelectedIndex()) for type safety. If nothing is selected, this will return null , which corresponds to the behavior of getSelectedItem() .

+55
Aug 11 2018-11-11T00:
source share

Here is the safe version:

 public static <T> T getSelectedItem(JComboBox<T> comboBox) { int index = comboBox.getSelectedIndex(); return comboBox.getItemAt(index); } 
0
Dec 03 '17 at 20:09 on
source share



All Articles