0

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

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,我如何添加所有项?

4

1 回答 1

3

take 的构造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());
于 2013-03-19T04:02:18.517 回答