我正在构建多个应用程序,JTables
我需要检测单元格值何时发生变化,以便我可以在数据库中更新它。我尝试过TableModelListener
覆盖tableChanged
,但只有在我编辑单元格后单击离开(单击另一行)时才会触发。
还有其他方法可以做到这一点吗?
我正在构建多个应用程序,JTables
我需要检测单元格值何时发生变化,以便我可以在数据库中更新它。我尝试过TableModelListener
覆盖tableChanged
,但只有在我编辑单元格后单击离开(单击另一行)时才会触发。
还有其他方法可以做到这一点吗?
您可以实现该CellEditorListener
接口,如本示例所示。请注意,JTable
它本身是一个CellEditorListener
.
失去焦点时终止编辑也可能很方便,如下所示:
table.putClientProperty("terminateEditOnFocusLost", true);
更多 Swing 客户端属性可以在这里找到。
我同意@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();