Samiey Mehdi
Samiey Mehdi

Reputation: 9414

How to bind an array to JComboBox dynamically?

I binding an array to JComboBox like the following:

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

but, I want to bind an array to JComboBox dynamically, like the following:

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

How to do it?

Upvotes: 1

Views: 1809

Answers (3)

Suresh Atta
Suresh Atta

Reputation: 121998

A little odd workaround(mine :)), might useful to you

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

Upvotes: 3

Roman C
Roman C

Reputation: 1

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

Upvotes: 1

Pierre
Pierre

Reputation: 35246

build your JComboBox with a dynamic ComboBoxModel

JComboBox(ComboBoxModel<E> aModel)

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

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

you can then add and remove elements:

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

or, if you only need to put the array in the combox:

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

Upvotes: 1

Related Questions