java 将数组的内容添加到组合框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4708289/
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
Add the contents of an array to a combo box
提问by sark9012
I have an array (in another class) with 10 values in. I want to add the values of this array into a combo box. Is this possible? Thanks
我有一个包含 10 个值的数组(在另一个类中)。我想将此数组的值添加到组合框中。这可能吗?谢谢
回答by Stewart Murrie
Sure:
当然:
Object[] yourArray = otherClass.getMyArray();
JComboBox box = new JComboBox (yourArray);
This will call Object.toString()
to get the value to display in the combo box, so if you are using a custom class make sure it overrides the toString()
method.
这将调用Object.toString()
以获取要显示在组合框中的值,因此如果您使用自定义类,请确保它覆盖该toString()
方法。
EDIT:
编辑:
There are a few ways to do this in Netbeans. Here's one way. Somewhere in your form, have a method like this:
在 Netbeans 中有几种方法可以做到这一点。这是一种方法。在你的表单中的某个地方,有一个这样的方法:
private ComboBoxModel getComboModel (OtherClass myOtherClass)
{
return new DefaultComboBoxModel (myOtherClass.getMyArray());
}
And then in the form designer:
然后在表单设计器中:
- click on the combo box
- edit the Model propert in the properties editor
- select Value from existing componentin the drop down
- select the Method callradio button and choose
getComboModel()
- 单击组合框
- 在属性编辑器中编辑模型属性
- 从下拉列表中的现有组件中选择值
- 选择方法调用单选按钮并选择
getComboModel()
There are many other ways to do it, but this will work for a simple case like yours. In general, if you want to make it Netbeans friendly, then you need to provide a method somewhere that returns an instance of ComboBoxModel and point Netbeans at it.
有很多其他方法可以做到这一点,但这适用于像您这样的简单案例。一般来说,如果你想让它对 Netbeans 友好,那么你需要在某处提供一个方法来返回 ComboBoxModel 的实例并将 Netbeans 指向它。
回答by Cratylus
Yes. In general you can do:
是的。一般来说,你可以这样做:
JComboBox b = new JComboBox(new String[]{"String1","String2"});
JComboBox b = new JComboBox(new String[]{"String1","String2"});
i.e. there is a contructor for initializing via arrays.
So you just have to override toString()
in the objects contained in the array(if they are not of type String) .
即有一个用于通过数组初始化的构造函数。
因此,您只需覆盖toString()
数组中包含的对象(如果它们不是 String 类型)。
回答by Ing. Antonio Gervasio Luelmo
Try this method:
试试这个方法:
private void combofill(){
cbxplaces.removeAllItems();
String[] place= {"Cont", "Cancel","TEST"};
DefaultComboBoxModel mod = new DefaultComboBoxModel(place);
cbxplaces.setModel(mod);
}