在 Jtable 中编辑单元格时获取特定列的总和

Get Sum of a Specific Column on Editing a Cell in Jtable

我正在尝试获取第 4 列的总和 typing/editing 第 4 列的值。我立即更改数字,即当我在第 4 列的任何行上键入时,它应该更改我设置的总和在 jTextField 上。

我尝试了 TableModelListener 和 ListSelectionListener,但效果不佳,因为我必须单击该行才能获得摘要。

jTable1.getModel().addTableModelListener(new TableModelListener(){
public void tableChanged(TableModelEvent evt){
    float sum = 0;
    int[] rows = jTable1.getSelectedRows();
    for(int i=0;i<jTable1.getRowCount();i++){
    try{
    sum = sum + 
Float.parseFloat(jTable1.getValueAt(rows[i],4).toString());
    }
    catch(Exception e){
    continue;
    }
    }
    jTextField15.setText(Float.toString(sum));
    getsummaries();
    }
});

我立即更改第 4 列的值,我希望它在 jTextField15 上自动求和。

我还没有找到解决办法。在 JTable 上键入时,很难记录总和。解决方法是创建一个按钮并计算 jTextField 上的总数。

it has not worked efficiently because i have to click on the row for it to get the summary.

模型仅在单元格失去焦点时更新,因为此时您键入的值将保存到模型中。这是因为您可以开始输入数字,然后使用 "escape" 键取消编辑。

如果您真的想在用户输入编辑器时更新总数,那么您需要向编辑器使用的文本字段添加 DocumentListener,而不是使用 TableModelListener:

DefaultCellEditor editor = (DefaultCellEditor)table.getDefaultEditor(Integer.class);
JTextField textField = (JTextField)editor.getComponent();
textField.getDocument().addDocumentListener(...);

有关更多信息和示例,请参阅 Listening For Changes on a Document 上的 Swing 教程部分。

当然这样做的话,还需要处理取消编辑的情况。因此,您还需要将 PropertyChangeListener 添加到 JTable 并监听 tableCellEditor 属性 变化。