What is the best way to listen for changes in JTab

2020-02-11 03:30发布

问题:

I'm building and app with multiple JTables and I need to detect when cell value change occurs so I can update it in the database. I tried TableModelListener and overriding tableChanged, but it fires only when I click away (click on another row) after I have edited a cell.

Any other way to do this?

回答1:

You can implement the CellEditorListener interface, as shown in this example. Note that JTable itself is a CellEditorListener.

It may also be convenient to terminate the edit when focus is lost, as shown here:

table.putClientProperty("terminateEditOnFocusLost", true);

More Swing client properties may be found here.



回答2:

I'm agreeing with @mKorbel - unless all your input is checkboxes and dropdowns, you're going to want to wait until the cell editing is stopped (you don't want to commit to the database every time a letter is typed in a textbox).

If the problem is that it's not committing after focus has gone to another component, add a FocusListener that stops editing the table when focus is lost on the table:

Example:

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


回答3:

I use the enter key so everytime a user hit enter the cell will update.

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

            }
        }
    });


回答4:

This is also handy if you want to stop the editing on an event handler from selection change or save button.

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