I’m having a problem while updating cell value of the JTable. What i want to do is after selection of a particular cell from the JTable, i should be able to edit and the action must reflect the database at the back end. I’m using HSQL. My table has 4 columns with one PK.
Kindly give me an alternative and/or provide me with some code by replacing the * s. I’m new just a beginner.
d_view.addActionListener(new ActionListener() { //----action listener of a button
public void actionPerformed(ActionEvent po) {
try {
Connection connec;
Class.forName("org.hsqldb.jdbcDriver");
connec = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/","SA", "");
java.sql.Statement stt=connec.createStatement();
ResultSet rs=stt.executeQuery("select * from DepReg");//----------TO VIEW DATA IN TABULAR FORMAT
ResultSetMetaData rt=rs.getMetaData();
int cols=rt.getColumnCount();
String c[] =new String[cols];
for(int i=0;i<cols;i++){
c[i]=rt.getColumnName(i+1);
dm.addColumn(c[i]);
}
Object row[]=new Object[cols];
while(rs.next()){
for(int i=0;i<cols;i++){
row[i]=rs.getString(i+1);
}
dm.addRow(row);
}
table.setModel(dm);
connec.close();
}
catch (Exception ty) {}
}
});//--------HERE THE PROBLEM STARTS
table.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent tme) {
int rows=tme.getFirstRow();
int colms=tme.getColumn();
TableModel model=(TableModel)tme.getSource();
String colname=model.getColumnName(colms);
Object data=model.getValueAt(rows, colms);
//*********EDIT/REPLACE THE CODE ***************//
try {
Connection connec;
Class.forName("org.hsqldb.jdbcDriver");
connec = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/","SA", "");
java.sql.Statement stt=connec.createStatement();
//-----------I WILL INCLUDE AN UPDATE STATEMENT OVER HERE BASED ON THE VALUE SELECTED
}
catch (Exception ae) {}
}
});
TableModelthat theisCellEditablemethod returnstruefor the cells you want to be editable, and that you have set aTableCellEditoron yourJTableTableModelListenerto update your database I would move that logic to a customTableModel. Every time thesetValueAtmethod is called, you know changes have been made. You can then update the database (again, not on the Event Dispatch Thread).TableModelto reflect the latest state of the database. Make sure you do the polling on a worker thread. Then you can either create a brand newTableModelon the worker thread, and replace theTableModelof the table on the Event Dispatch Thread. Or you can update the existing model on the EDT (do not forget to fire events, or if your model extends fromDefaultTableModel/AbstractTableModelyou can use the available API).I also recommend reading the Swing table tutorial for more info.