Binding a JComboBox to a List

Here is a method to bind a list to a combo box.

Hope it will be helpful

public ComboBoxModel cityModel(List<cityDetail>cityList ) {
ComboBoxModel model;

if (cityList == null || cityList.size() <= 0) {
Object[] d = new Object[1];
//d[0] = “None”;
ComboBoxModel mo = new DefaultComboBoxModel(d);
return mo;
}

Object[] days = new Object[cityList.size() + 1];
int i = 0;
try {
ListIterator<CityDetails> lg = cityList.listIterator();
while (lg.hasNext()) {
CityDetails newcus = lg.next();
days[i] = newcus.getCityname();
i = i + 1;
}

days[i] = “Add New”;
} catch (Exception ex) {
System.out.println(“error occured ” + ex.toString());
}
model = new DefaultComboBoxModel(days);
return model;
}
this.cbCity.setModel(cityModel())

//where cbCity is the jcombobox

Populating a JTable with a Collection (List)

Below is a method for populating a Jtable using a List(Collection)

Hope it will be helpful


private void DisplayData(List<productdetail>ProductsList) {
DefaultTableModel aModel = new DefaultTableModel() {
//setting the jtable read only

@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
//setting the column name
Object[] tableColumnNames = new Object[2];
tableColumnNames[0] = “Product Name”;
tableColumnNames[1] = “Description”;

aModel.setColumnIdentifiers(tableColumnNames);
if (ProductsList == null) {
this.tbProducts.setModel(aModel);
return;
}

Object[] objects = new Object[2];
ListIterator<productsdetail> lstrg = ProductsList.listIterator();
//populating the tablemodel
while (lstrg.hasNext()) {
productsdetail newcus = lstrg.next();
objects[0] = newcus.getProductName();
objects[1] = newcus.getDescription();

aModel.addRow(objects);
}

//binding the jtable to the model
this.tbProducts.setModel(aModel);
}