3

I've seen my question asked several times but I never saw the answer I expected. I've entered elements of a database in a JTable and I want to be able to delete/add elements via some JButtons. The problem is that when I add/delete, the modification is visible in the database but not in the JTable. When I stop the programm and run it again, the JTable is updated. What could I do to update the table immediatly after the modification of a row? I've tried to do this.table.repaint() but it didn't work. I think I'll have to do something with the tablemodel, probably with fireTableStructureChanged(); but I don't undersand well how to use it Thank you very much for your time.

Here's part of my code in the controller class of the JTable, I don't think it will help..

public void update(Observable o, Object message) {
    Integer iMessage = (Integer) message;

    if (iMessage == Cours.CHANGEMENT_ELEVES) {
        int sizeEl = this.modele.getAllEleves().size();

        if (this.modele.getAllEleves() !=null) {
            Vector<String[]> data = this.modele.getAllEleves();

            for (int i=0; i<sizeEl; i++) {
                this.table.setValueAt(data.get(i)[0],i, 0);
                this.table.setValueAt(data.get(i)[1],i,1);
                this.table.setValueAt(data.get(i)[2],i,2);
        }
        this.table.repaint();
    }
    }
}
vinothp
  • 9,939
  • 19
  • 61
  • 103
morg
  • 1,173
  • 4
  • 18
  • 36

2 Answers2

0

Please add the following code when you want synchronize the JTable With The DataBase.

        // Here Add Your Data Fetch Code From DataBase 
        For e.g.
       Vector<Object> objVect_Dt = util.GetQueryResultSet(query);
       Vector<Vector<String>> data = (Vector<Vector<String>>) objVect_Dt.get(1);
       Vector<String> header = (Vector<String>) objVect_Dt.get(0);

After fetching the data from DataBase Update The Table Model as

        DefaultTableModel dtm = new DefaultTableModel(data, header);
        Table.setModel(dtm);
         table.repaint();
0

Its not a problem of Jtable repaint or revalidate. When u add row or delete row from table model, u must fire event fireTableRowInserted even or tableDatachangeEvent. Following code is example:

class myModel extends AbstractTableModel
{
////
////
////
////
////
       // Remove Row from table Model
        public void removeRow(int row) {
            data.removeElementAt(row);
            fireTableRowsDeleted(getRowCount(), getRowCount());
        }

        // Add new row to table
        public void addRow(Vector row) {
            data.addElement(row);
            fireTableRowsInserted(0, getRowCount());
        }
}
Chaitanya
  • 37
  • 1
  • 5