【问题标题】:How to make a jtable cell listen to changes from another cell如何使 jtable 单元格监听来自另一个单元格的更改
【发布时间】:2012-05-21 17:33:32
【问题描述】:

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

【问题讨论】:

    标签: java jtable cell custom-cell focuslistener


    【解决方案1】:

    单元格编辑器最终会在您的表格模型上调用方法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  
            }
            // ...
        }
    }
    

    【讨论】:

    • 嗯.. 我没明白。对不起!你能进一步解释一下还是伪代码?谢谢顺便说一句。
    • 我想出了自己的解决方案。我使用了 TableModelListener 中的 tableChanged。还是谢谢你!
    • @user1349213:您应该在 model 中执行此操作,如 JB 所示;有一个相关的例子here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多