问题
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