如何使jtable单元格侦听来自另一个单元格的更改

时间:2012-05-14 08:30:51

标签: java jtable cell custom-cell focuslistener

请帮忙。我有一个来自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));

1 个答案:

答案 0 :(得分:3)

单元格编辑器将在表模型上超级调用方法setValueAt()。在此表模型中,除了编辑的celle值之外,只需更新链接的单元格值,并为两个单元格触发相应的更改事件。

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  
        }
        // ...
    }
}