Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select item in jComboBox

Tags:

java

swing

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

like image 964
jtnire Avatar asked May 05 '10 21:05

jtnire


People also ask

How do you check what is selected in a JComboBox?

You can use JComboBox#getSelectedIndex , which will return -1 if nothing is selected or JComboBox#getSelectedItem which will return null if nothing is selected.

Which event gets generated when you select an item from a JComboBox?

Combo boxes also generate item events, which are fired when any of the items' selection state changes.

What is the difference between JList and JComboBox?

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.


1 Answers

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.

like image 178
Matthieu BROUILLARD Avatar answered Oct 17 '22 18:10

Matthieu BROUILLARD