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) {}
}
});
TableModel
that the isCellEditable
method returns true
for the cells you want to be editable, and that you have set a TableCellEditor
on your JTable
TableModelListener
to update your database I would move that logic to a custom TableModel
. Every time the setValueAt
method is called, you know changes have been made. You can then update the database (again, not on the Event Dispatch Thread). TableModel
to reflect the latest state of the database. Make sure you do the polling on a worker thread. Then you can either create a brand new TableModel
on the worker thread, and replace the TableModel
of 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 from DefaultTableModel
/ AbstractTableModel
you can use the available API). I also recommend reading the Swing table tutorial for more info.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.