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?
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.
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...
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);
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();
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With