0

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?

NotMe
  • 87,343
  • 27
  • 171
  • 245
kelvzy
  • 913
  • 2
  • 12
  • 19
  • You want to add values to `DefaultComboBoxModel ` or `DefaultTableModel` ? – Apurv Mar 19 '13 at 03:58
  • 4
    1) Use a consistent and logical indent for code blocks. The indentation of the code is intended to help people understand the program flow. 2) For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Mar 19 '13 at 04:00
  • 3
    See [*Using a Combo Box as an Editor*](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#combobox). – trashgod Mar 19 '13 at 04:01
  • add items in my combox from table @Apurv – kelvzy Mar 19 '13 at 04:23
  • the list of rs are in MySQL, so when I call the items I want I Will put it all in the ITEMS of my combobox @Apurv – kelvzy Mar 19 '13 at 04:35

1 Answers1

3

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());
Apurv
  • 3,723
  • 3
  • 30
  • 51