Add the contents of an array to a combo box
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
Yes. In general you can do:
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) .
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.
EDIT:
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());
}
And then in the form designer:
- 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()
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.
Try this method:
private void combofill(){
cbxplaces.removeAllItems();
String[] place= {"Cont", "Cancel","TEST"};
DefaultComboBoxModel mod = new DefaultComboBoxModel(place);
cbxplaces.setModel(mod);
}
精彩评论