How to add multiple items to the DefaultComboBoxModel

て烟熏妆下的殇ゞ 提交于 2019-12-13 03:07:21

问题


I have the following code but I don't know how to add all of the items to my combobox.

DefaultTableModel rs = MyDB.DataTable("SELECT `Activity` FROM `transactions` WHERE `Group` = '" + Gname.getText()+ "' OR `Group` = 'ALL'");

DefaultComboBoxModel dmc = new DefaultComboBoxModel();

dmc.addElement("");

if (rs.getRowCount() > 0) {
    dmc.addElement(rs.getValueAt(0,0).toString());
}

cboItem.setModel(dmc);

It only adds one item to my DefaultTableModel, how can I add all of them?


回答1:


The constructor of DefaultComboBoxModel takes Object[]. You can first iterate over the rs values prepare an array (or list) and then pass this array to DefaultComboBoxModel constructor. Like this ...

DefaultTableModel rs = MyDB.DataTable("SELECT `Activity` FROM `transactions` WHERE `Group` = '" + Gname.getText()+ "' OR `Group` = 'ALL'");
int columnCount = rs.getColumnCount();
int rowCount = rs.getRowCount();

List <Object> values = new ArrayList<Object>();
for (int rowIndex = 0; rowIndex < rowCount; rowIndex ++){
    for(int columnIndex = 0; columnIndex < columnCount; columnIndex++){
         Object value = rs.getValueAt(rowIndex , columnIndex );
         values.add(value);
    }
}
DefaultComboBoxModel dmc = new DefaultComboBoxModel(values.toArray());


来源:https://stackoverflow.com/questions/15491211/how-to-add-multiple-items-to-the-defaultcomboboxmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!