Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to listen for changes in JTable cell values and update database accordingly?

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?

like image 966
Igor Avatar asked Oct 10 '12 15:10

Igor


People also ask

How can you change the appearance of data in cells in JTable?

We can change the background and foreground color for each column of a JTable by customizing the DefaultTableCellRenderer class and it has only one method getTableCellRendererComponent() to implement it.

How add data from database to JTable in Java?

Load the data from the database... String sql="SELECT * FROM hwList"; ResultSet rs = st. executeQuery(sql); Add each row of data to the table model...

What is JTable TableModel?

The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model. The JTable can be set up to display any data model which implements the TableModel interface with a couple of lines of code: TableModel myData = new MyTableModel(); JTable table = new JTable(myData);


2 Answers

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();
    }
});
like image 149
Nick Rippe Avatar answered Oct 23 '22 21:10

Nick Rippe


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.

like image 27
trashgod Avatar answered Oct 23 '22 20:10

trashgod