JAVA update database on JTable cell change

22,065

A deleted answer plagiarised Rachel Swailes' answer from 14 years ago, found here. For completeness and because the answer is correct and useful, I have quoted the relevant text here:

Step 1: It's going to be way easier for the whole thing if you make your table extend a TableModel from now (if you haven't already). So if you need help with that just ask.

Step 2: In the table model you need to enable the cells to be editable. In the TableModel class that you make, you need to add these methods

public boolean isCellEditable(int row, int col) { 
  return true; 
}

public void setValueAt(Object value, int row, int col) {
  rowData[row][col] = value;
  fireTableCellUpdated(row, col);
}

Step 3: You will see in the second method that we fire a method called fireTableCellUpdated. So here we can catch what the use it changing. You need to add a TableModelListener to your table to catch this.

mytable.getModel().addTableModelListener(yourClass);

And in the class that you decide will implement the TableModelListener you need this

public void tableChanged(TableModelEvent e) {
  int row = e.getFirstRow();
  int column = e.getColumn();
  TableModel model = (TableModel)e.getSource();
  Object data = model.getValueAt(row, column);
  ...
}

now you have the data in the cell and the place in the grid where the

cell is so you can use the data as you want

Share:
22,065
botenvouwer
Author by

botenvouwer

I'm a GEO/IT consultant in holland

Updated on July 09, 2022

Comments

  • botenvouwer
    botenvouwer almost 2 years

    He I am noob to Java (Thats not new) and I can't find a good tutorial for this. I use jTable to display a table filled with data from a MySQL database.

    So far so good, I get the table:

    table preview

    Standard you can click a table cell and it changes to a text-field with can be filled with something new. You all know that, but how can I use this to also update the value in my database?

    My code:

    import [...];
    public class table extends JPanel {
        public String table;
        private Database db;
    
        public table(String tablename, Database db){
    
            try {
                table = tablename;
                this.db = db;
    
                //Get table with and height
                ResultSet res = db.query("SELECT COUNT( * ) FROM `"+table+"`");
                ResultSet res2 = db.query("SELECT COUNT( * ) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '"+table+"'");
    
                int rows = 0;
                int collums = 0;
    
                res.next();
                res2.next();
    
                rows = res.getInt(1);
                collums = res2.getInt(1);
    
                //Get table column names and set then in array
                ResultSet clom = db.query("DESCRIBE  `"+table+"`");
    
                String[] columnNames = new String[collums];
    
                int s = 0;
    
                while(clom.next()){
                    columnNames[s] = clom.getString(1);
                    s++;
                }
    
                //get table data and put in array
                Object[][] data = new Object[rows][collums];
    
                ResultSet result = db.query("SELECT * FROM `"+table+"`");
    
                int q = 0;
    
                while(result.next()){
                    for(int a=0; a<= (collums - 1); a++){
                        data[q][a] = result.getString(a + 1);
                        //System.out.println(q + " - " + a);
                    }
                    q++;
                }
    
                //Make Jtable of the db result form the two array's
                final JTable table = new JTable(data, columnNames);
                table.setPreferredScrollableViewportSize(new Dimension(500, 70));
                table.setFillsViewportHeight(true);
    
                // do some event listening for cell change
    
                JScrollPane scrollPane = new JScrollPane(table);
                JFrame frame = new JFrame("table editor");
                scrollPane.setOpaque(true);
                frame.setContentPane(scrollPane);
                frame.pack();
                frame.setSize(600, 800);
                frame.setVisible(true);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
    }
    

    I guess I need to bind some kind of table listener and when something changes I take all the values of the table and update them with a query.

    How can I do this?

    This is my pseudo code:

    table.bindCellEventListner(callback(t){
         Array row = t.getAllValuesAsArrayOfRow();
    
         String data = "";
    
         int f = 0
         while(row.next()){
             data .= "`"+clom[f]+"` = '"+row[f]+"',"
             f++;
         }
         data.delLastChar();
         db.query("UPDATE `"+table+"` SET "+data+" WHERE `id` ="+row[0]+";");
    
    });