2

Please help. I have two cells from a jtable, one ID and one Description. The ID and Description are both custom combobox. What I am trying to do is when the ID loses its focus or changes its value, the Description will update based on the value on the ID. How do I do that?

Here is my code for the implementation of both cells:

TableColumn subAccountCol = jTable1.getColumnModel().getColumn(table.findColumn("SubAccount"));

    javax.swing.JComboBox accountCbx = new javax.swing.JComboBox(Account.toArray());
    javax.swing.JComboBox accountDescCbx = new javax.swing.JComboBox(AccountDesc.toArray());

    CompleteText.enable(accountCbx);
    CompleteText.enable(accountDescCbx);

    jTable1.getColumnModel().getColumn(table.findColumn("Account")).setCellEditor(new ComboBoxCellEditor(accountCbx));
    jTable1.getColumnModel().getColumn(table.findColumn("Account Description")).setCellEditor(new ComboBoxCellEditor(accountDescCbx));

1 Answer 1

3

The cell editor will ultmately call the method setValueAt() on your table model. In this table model, simply update the linked cell value in addition to the edited celle value, and fire the appropriate change event for both cells.

public MyTableModel extends AbstractTableModel() {
    // ...

    // modifies the value for the given cell
    @Override
    public void setValueAt(Object value, int row, int column) {
        Foo foo = this.list.get(row);
        if (column == INDEX_OF_ID_COLUMN) {
            foo.setId(value); // change the ID
            fireTableCellUpdated(row, column); // signal the the ID has changed
            // and now also change the description
            String newDescription = createNewDescription(value);
            foo.setDescription(newDescription);
            fireTableCellUpdated(row, INDEX_OF_DESCRIPTION_COLUMN); // signal the the description has changed  
        }
        // ...
    }
}
3
  • Umm.. I didnt get that. Sorry! Can you explain it further or a pseudocode maybe? Thanks btw.
    – John
    May 14, 2012 at 8:39
  • I was able to come up with my own solution. I used the tableChanged from the TableModelListener. Thank you anyway!
    – John
    May 14, 2012 at 9:32
  • @user1349213: You should do this in the model, as JB shows; there's a related example here.
    – trashgod
    May 14, 2012 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.