Heya guys,

I am trying to make a desktop application for my assignment. I have to design an application that will have a JTable, JTextField and Buttons. I am done the GUI part. The input that user enters into the table should get stored into the database using an "insert" button(using JDBC). I know how to connect to the database and how to insert stuff into it. But I do not understand how can i edit my table and after the table is edited. The database should update. Also, how can i send string objects(input from the JTextField) into the database using a query?

P.S. I am using model for table

final DefaultTableModel model = new DefaultTableModel(data, col);
        final JTable table = new JTable(model);

Thanks :)

Hey,

I had the exact same problem. I found an answer here:

http://download.oracle.com/javase/tutorial/uiswing/components/table.html - Listening for Data Changes:

public class SimpleTableDemo ... implements TableModelListener {
    ...
    public SimpleTableDemo() {
        ...
        table.getModel().addTableModelListener(this);
        ...
    }

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

        ...// Do something with the data...
    }
    ...
}

You can see which cell in your table has changed, so you can make a String containing a query for updating that database entry.

update TABLE set field= data (from the code quoted above) where id= model.getValueAt(X, Y);

X, Y = the row and column indexes where your ID is shown on the table.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.