为什么ComboBoxModel <e>返回Object而不是E.

时间:2017-09-10 12:46:19

标签: java swing

使用Swing的ComboBoxModel,获取所选元素时需要输入类型,因为接口定义如下:

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

    void setSelectedItem(Object anItem);

    Object getSelectedItem();

}

我认为getSelectedItem的返回类型可能是E。 实际上,这是由ListModel继承的ComboBoxModel接口完成的,用于按索引选择:

public interface ListModel<E> {

   E getElementAt(int index);

}

E中不使用ComboBoxModel类型参数的原因是什么?

1 个答案:

答案 0 :(得分:0)

因为用户可以编辑ComboBox文本字段。

JComboBox.setEditable(true);

如果ComboBox是可编辑的,则用户可以在ComboBox Textfield中输入Text,无论为模型提供什么类型参数,JrcboBox.getSelectedItem()都会返回String。

如果您想获得E使用的对象:

  E e = JComboBox.getModel().getElementAt(JComboBox.getSelectedIndex());
相关问题