如何将多个项添加到DefaultComboBoxModel

时间:2013-03-19 03:55:26

标签: java swing defaulttablemodel

我有以下代码,但我不知道如何将所有项目添加到我的组合框中。

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

它只会向我的DefaultTableModel添加一个项目,如何添加所有项目?

1 个答案:

答案 0 :(得分:3)

DefaultComboBoxModel的构造函数需要Object[]。您可以首先遍历rs值,准备一个数组(或列表),然后将此数组传递给DefaultComboBoxModel构造函数。像这样......

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());