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

问题描述 投票:8回答:4

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

还有其他办法吗?

java swing jtable listener tablemodel
4个回答
17
投票

你可以实现CellEditorListener接口,如example所示。请注意,JTable本身就是一个CellEditorListener

在焦点丢失时终止编辑也很方便,如here所示:

table.putClientProperty("terminateEditOnFocusLost", true);

可以找到更多Swing客户端属性here


4
投票

我同意@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();
    }
});

0
投票

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

    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);

            }
        }
    });

0
投票

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

if (table.isEditing())
    table.getCellEditor().stopCellEditing();
© www.soinside.com 2019 - 2024. All rights reserved.