开发者

How to select item in jComboBox

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 sa开发者_运维问答me letter

Thanks


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.


It is simple if you have your jcombobox in design mode.

In source mode, to get the selected item, the only thing that you need is converting the item selected in String.

Like this:

String cap=jgrado.getSelectedItem().toString();

After that you can save the Item for example:

pps2.setString(8,cap);

or in a jtextpane:

jtextpane.setText(jgrado.getSelectedItem().toString());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜