How to save the new values from cells, not the old ones?
I have a JTable in a JScrollPane and the data comes from a database. Cells are editable, and I want to save the new values (the edited ones) in the database. The problem is that getValueAt(row, col) returns the old, unedited values.
Here is the code that takes the values 开发者_Python百科from cells and insert them in the database.
DefaultTableModel tableModel = (DefaultTableModel) table.getModel(); int row = table.getEditingRow(); if(row == -1) return -1; String name = tableModel.getValueAt(row, 0).toString(); String stringPrice = tableModel.getValueAt(row, 1).toString(); float price = Float.parseFloat(stringPrice); products.updateProduct(name, price); ... return 1;
And here is what I get in the updateProduct(name, price) method:
UPDATE products SET `prod_name` = 'OLD_NAME', `prod_price` = 'OLD_PRICE' WHERE `id` = 4
instead of:
UPDATE products SET `prod_name` = 'NEW_NAME', `prod_price` = 'NEW_PRICE' WHERE `id` = 4
There might be a simple solution, but I can't figure it out. Any help is appreciated.
Without knowing exactly how your code snipped is invoked I would guess that your problem is that the cell editor has not been stopped so the model has not yet been updated with the new data.
You can use a TableModelListener to be notified when data in a cell changes. Then you are guaranteed that the data in the model is correct.
Or, if you are using a "Save" button to update the database, then you need to read Table Stop Editing for the solution to your problem.
You could implement your own cell editor, and use its current value instead of the value in the model if it's active
精彩评论