I just read the JavaDoc for JComboBox (I promise I have a life... I wasn't reading through for fun. =P), and I think 开发者_Go百科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?
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.
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()
final Object object = jComboBox.getEditor().getItem();
if (object instanceof String) {
final String string = (String)object;
}
Useful for cases when you allow certain input outside the supplied range of values in the combobox model.
精彩评论