views:

414

answers:

4

I just read the JavaDoc for JComboBox (I promise I have a life... I wasn't reading through for fun. =P), and I think the problems I'm having with my program can be attributed to the getSelectedItem() method. The documentation says:

Returns the current selected item.

If the combo box is editable, then this value may not have been added to the combo box with addItem, insertItemAt or the data constructors.

If you can't get values that were added with those methods or with the constructor, of what use is the method? And how can I get the value from an "editable" JComboBox?

Link to JavaDoc: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComboBox.html#getSelectedItem()

+1  A: 

the extra value added by the user in the JComboxBox will not be added in the ComboBoxModel but will be available as a java.lang.String via getSelectedItem()

Pierre
A: 
final Object object = jComboBox.getEditor().getItem();
if (object instanceof String) {
    final String string = (String)object;
}
Yan Cheng CHEOK
A: 

Useful for cases when you allow certain input outside the supplied range of values in the combobox model.

+1  A: 

If you can't get values that were added with those methods or with the constructor, of what use is the method? And how can I get the value from an "editable" JComboBox?

That's not what the docs say. The docs say the selected item might not have been added with add/insertItem , which might very well be the case if the user edited/typed in the value himself.

In any case, getSelectedItem() gives you whatever is selected in the combobox, wether it was one of the values you filled in, or one the user typed.

nos
Ahh, thank you. I misinterpreted. I was taking "editable" to mean "mutable."
Chris Cooper