如何动态绑定数组到JComboBox?

问题描述 投票:0回答:3

我将数组绑定到

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     
}

如何做?

java arrays swing jcombobox comboboxmodel
3个回答
3
投票

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

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

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")

或者,如果您只需将数组放入组合框中:

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

1
投票
final JComboBox lstA = new JComboBox();
void bind()
{
  String[] arr={"ab","cd","ef"};
  // bind arr to lstA 
  lstA.setModel(new DefaultComboBoxModel<String>(arr));    
}
© www.soinside.com 2019 - 2024. All rights reserved.