监听JTable单元值更改并相应更新数据库的最佳方法是什么?

我正在使用多个JTables构建和应用程序,我需要检测何时发生单元格值更改,以便我可以在数据库中更新它。 我尝试了TableModelListener并覆盖了tableChanged ,但只有在我编辑tableChanged单元格后单击 (单击另一行) 才会触发。

还有其他办法吗?

您可以实现CellEditorListener接口,如此示例所示。 请注意, JTable本身是一个CellEditorListener

在焦点丢失时终止编辑也很方便:

 table.putClientProperty("terminateEditOnFocusLost", true); 

我同意@mKorbel – 除非您的所有输入都是复选框和下拉列表,否则您将要等到单元格编辑停止(每次输入一个字母时都不想提交数据库)文本框)。

如果问题是在焦点转到另一个组件后它没有提交,请添加一个FocusListener ,当焦点丢失在表上时停止编辑表:

例:

 final JTable table = new JTable(); table.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { TableCellEditor tce = table.getCellEditor(); if(tce != null) tce.stopCellEditing(); } }); 

我使用回车键,所以每次用户点击进入时,单元格都会更新。

  DefaultTableModel dtm = new DefaultTableModel(data, columnNames); JTable table = new JTable(dtm); table.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { int row = table.getSelectedRow(); int column = table.getSelectedColumn(); // resul is the new value to insert in the DB String resul = table.getValueAt(row, column).toString(); // id is the primary key of my DB String id = table.getValueAt(row, 0).toString(); // update is my method to update. Update needs the id for // the where clausule. resul is the value that will receive // the cell and you need column to tell what to update. update(id, resul, column); } } }); 

如果要从选择更改或保存按钮停止对事件处理程序的编辑,这也很方便。

 if (table.isEditing()) table.getCellEditor().stopCellEditing();