0

I have a table that displays the data: ID, NAME, CATEGORY, COMPANY. Data is retrieved from the database. I would like to add a ComboBox to the column CATEGORY. So as to be able to choose any category that they are in the database.

List<Item> item;
JTable itemTable = new JTable();
JScrollPane itemScroll = new JScrollPane();
DefaultTableModel itemmodel = new DefaultTableModel();

        itemmodel.setRowCount(0);
        item = model.getItem();

        for (Item ite : item) {
            itemmodel.addRow(new Object[] { ite.getId(), ite.getName(),
                    ite.getCategory(), ite.getCompany() });
        }
        item.clear();

Then I add the data to the JFrame properly and everything displays. I read the documentation, but I do not know how to use the examples in my case.

To display the same categories have separate jTable and data downloading via

        tablemodel.setRowCount(0);
        category = model.getCategory();

        for (Category cat: categoryList) {
            tablemodel
                    .addRow(new Object[] { cat.getId(), cat.getName() });
        }
        categoryList.clear();
mKorbel
  • 109,525
  • 20
  • 134
  • 319
lukassz
  • 127
  • 1
  • 2
  • 12

2 Answers2

2

You can fetch the categories from the database using the approach shown here or here. You can specify the resulting JComboBox as a table column's CellEditor using the approach shown here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

I solved it this way and it looks great. Is this the solution is correct? How do I store category id in Combobox?

        itemmodel.setRowCount(0);
        item = model.getItem();

        people = model.getCategory();

        for (Category cate : categoryList) {
            categoryBox.addItem(cate.getName());
        }
        for (Item ite : item) {
            itemmodel.addRow(new Object[] { ite.getId(),ite.getName(),  
                    ite.getCategory(), ite.getCompany() });
        }
        item.clear();

        TableColumn categoryColumn = itemTable.getColumnModel().getColumn(2);
        categoryColumn.setCellEditor(new DefaultCellEditor(categoryBox));
lukassz
  • 127
  • 1
  • 2
  • 12
  • 1
    `DefaultComboBoxModel` can hold arbitrary elements characterized by a generic type parameter; you can change the displayed name as shown [here](http://stackoverflow.com/q/25432381/230513). – trashgod Aug 21 '14 at 18:47
  • Ok, but I change addItem to `companyBox.addItem(new Company(comp.getId(), comp.getName(), null));` and I just call in my ActionListener for ComboBox `Category selected_category = (Category) categoryBox.getSelectedItem();` – lukassz Aug 21 '14 at 18:54