2

请帮忙。我有两个来自 jtable 的单元格,一个 ID 和一个描述。ID 和描述都是自定义组合框。我要做的是当 ID 失去焦点或更改其值时,描述将根据 ID 上的值更新。我怎么做?

这是我实现两个单元的代码:

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));
4

1 回答 1

3

setValueAt()单元格编辑器最终会在您的表格模型上调用该方法。在此表格模型中,除了编辑的单元格值之外,只需更新链接的单元格值,并为两个单元格触发适当的更改事件。

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  
        }
        // ...
    }
}
于 2012-05-14T08:34:06.867 回答