3

Using Swing's ComboBoxModel, type casting is required when getting the selected element, as the interface is defined as follows:

public interface ComboBoxModel<E> extends ListModel<E> {

    void setSelectedItem(Object anItem);

    Object getSelectedItem();

}

I would think the return type of getSelectedItem could be E. In fact, this is done by the ListModel interface the ComboBoxModel inherits from, for selecting by index:

public interface ListModel<E> {

   E getElementAt(int index);

}

What would be the reason to not use the E type parameter in ComboBoxModel?

c0der
  • 18,467
  • 6
  • 33
  • 65
CounterFlame
  • 1,612
  • 21
  • 31

1 Answers1

0

Because a ComboBox Textfield may be editable by the user.

JComboBox.setEditable(true);

If a ComboBox is editable the user may enter Text to the ComboBox Textfield which is returned as String by JComboBox.getSelectedItem() no matter what type parameter was provided for the model.

If you want to get a object of E use:

  E e = JComboBox.getModel().getElementAt(JComboBox.getSelectedIndex());