java 如何在 jComboBox 中选择项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2777045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:47:08  来源:igfitidea点击:

How to select item in jComboBox

javaswing

提问by jtnire

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.

我有一个 jComboBox,我正在用一些对象填充它。这些对象是我自己制作的类型,包括一个字符串和一个整数。对象的 toString 方法返回显示在组合框中的字符串。

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

谢谢

回答by Matthieu BROUILLARD

I guess it is as simple as looking in the javadocs & tutorials: How to Use Combo Boxes

我想它就像查看 javadocs 和教程一样简单:如何使用组合框

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.

编辑:setSelectedItem 在模型的对象上使用内部等于。因此,如果模型中对象的 equals 方法适用于对象类的“int”属性,那么即使两个对象具有相同的“String”属性,它也会按预期工作。

回答by George Roman

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

如果您的 jcombobox 处于设计模式,这很简单。

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

在源模式下,要获取所选项目,您唯一需要做的就是转换在 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 中:

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