将数组的内容添加到组合框中 [英] Add the contents of an array to a combo box
问题描述
我有一个数组(在另一个类中),其中包含10个值。
我想将此数组的值添加到组合框中。
这可能吗?
谢谢
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
推荐答案
当然:
Object[] yourArray = otherClass.getMyArray();
JComboBox box = new JComboBox (yourArray);
这将调用 Object.toString()
获取要在组合框中显示的值,因此如果您使用自定义类,请确保它覆盖 toString()
方法。
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.
编辑:
在Netbeans中有几种方法可以做到这一点。这是一种方式。在表单的某处,有这样的方法:
There are a few ways to do this in Netbeans. Here's one way. Somewhere in your form, have a method like this:
private ComboBoxModel getComboModel (OtherClass myOtherClass)
{
return new DefaultComboBoxModel (myOtherClass.getMyArray());
}
然后在表单设计器中:
- 点击组合框
- 在属性编辑器中编辑Model属性
- 选择现有组件的价值 下拉列表
- 选择方法调用单选按钮,然后选择
getComboModel()
- click on the combo box
- edit the Model propert in the properties editor
- select Value from existing component in the drop down
- select the Method call radio button and choose
getComboModel()
还有很多其他方法可以做到这一点,但这适用于像你这样的简单案例。一般来说,如果你想使Netbeans友好,那么你需要提供一个返回ComboBoxModel实例的方法并指向它的Netbeans。
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.
这篇关于将数组的内容添加到组合框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!