abc soeasy
abc soeasy

Reputation: 1

Refreshing jTable with Database with Netbeans

I am developing a database application with Java and with MySQL as database. Am using Netbeans as a developing Tool.

I need to display the stored database in a JTable.

Now when I add data to the database via query. The JTable is not showing the updated details instantly. I need to restart the application i.e. run it again.

Now I need to know how do I refresh the JTable when there is a change in DB.

Please provide me the steps or sample coding because I am not able to find a certain coding example on Internet.

Upvotes: 0

Views: 13021

Answers (4)

Ayvadia
Ayvadia

Reputation: 339

You could also use the following code if you have instanciated tableNameList as observable:

tableNameList.clear();
tableNameList.addAll(tableQuery.getResultList());

Upvotes: 0

Ankur pandey
Ankur pandey

Reputation: 61

I faced the same problem, then i created the function named "UPDATEtable()" in which I put the connectivity code and called that function when it was needed to input data in Jtable from Mysql. For Refresh button , i first cleared the data from the table and then called the same function.

Here is the code :-(Table Variable name - TB1)

private void **UPDATEtable()**{
        DefaultTableModel model=(DefaultTableModel) TB1.getModel();
try{



  stmt= con.createStatement();
    String query="SELECT * FROM goods ORDER BY order_num DESC;";
ResultSet rs = stmt.executeQuery(query);
    while(rs.next()){
        String PID = rs.getString("PID");
     String Pname = rs.getString("Pname");
       String NUM = rs.getString("order_num");
      model.addRow(new Object[] {PID ,Pname,NUM);

    }


}


catch(Exception e)
{
    System.out.print(e);

}

FOR REFRESH BUTTON :-

    DefaultTableModel model=(DefaultTableModel) TB1.getModel();
        while(model.getRowCount()>0){
    model.setRowCount(0);
}

        UPDATEtable();

Upvotes: 1

camickr
camickr

Reputation: 324147

Whenever data in the database changes you need to recreate the TableModel and then update the table with the new model:

TableModel model = ...

table.setModel( model );

Upvotes: 2

Jack
Jack

Reputation: 133609

Maybe it's enough to fire changes through the table model:

yourTable.getModel().fireTableDataChanged()

Upvotes: 2

Related Questions