I have a jComboBox that I am populating with some objects. The objects are of a type which I have made myself, and include a String and an int. The object's toString method returns the String, which is displayed in the Combo Box.
Now, I wish to select an item in the Combo Box with code. How do I do this?
There are multiple items starting with the same letter
Thanks
You can use JComboBox#getSelectedIndex , which will return -1 if nothing is selected or JComboBox#getSelectedItem which will return null if nothing is selected.
Combo boxes also generate item events, which are fired when any of the items' selection state changes.
A JComboBox is a component that displays a drop-down list and gives users options that we can select one and only one item at a time whereas a JList shows multiple items (rows) to the user and also gives an option to let the user select multiple items.
I guess it is as simple as looking in the javadocs & tutorials: How to Use Combo Boxes
JComboBox j = something;
...
j.setSelectedIndex(anIndex);
// or
j.setSelectedItem(anObject);
EDIT: the setSelectedItem uses internally equals on the objects of the Model. So if the equals method of the Objects that you have in your model works on the "int" property of your object class then it will work as you expect even if two objects have the same "String" property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With