如何动态地将数组绑定到JComboBox?

时间:2013-10-06 09:24:24

标签: java arrays swing jcombobox comboboxmodel

我将数组绑定到JComboBox,如下所示:

String[] arr={"ab","cd","ef"};
final JComboBox lstA = new JComboBox(arr);

但我希望动态绑定数组JComboBox如下:

final JComboBox lstA = new JComboBox();
void bind()
{
    String[] arr={"ab","cd","ef"};
    // bind arr to lstA     
}

怎么做?

3 个答案:

答案 0 :(得分:3)

一个奇怪的解决方法(我的:)),可能对你有用

final JComboBox lstA = new JComboBox();
String[] arr={"ab","cd","ef"};
lstA.setModel(new JComboBox(arr).getModel());

答案 1 :(得分:1)

使用动态ComboBoxModel

构建您的JComboBox
JComboBox(ComboBoxModel<E> aModel)

喜欢http://docs.oracle.com/javase/7/docs/api/javax/swing/DefaultComboBoxModel.html

m=new DefaultComboBoxModel();
j=JComboBox(m);

然后您可以添加和删除元素:

m.addElement("ab")
m.addElement("cd")

或者,如果您只需要将数组放在combox中:

new JComboBox(new Sring[]{"ab","cd","ef"})

答案 2 :(得分:1)

final JComboBox lstA = new JComboBox();
void bind()
{
  String[] arr={"ab","cd","ef"};
  // bind arr to lstA 
  lstA.setModel(new DefaultComboBoxModel<String>(arr));    
}