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 que开发者_StackOverflowry. 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.
Maybe it's enough to fire changes through the table model:
yourTable.getModel().fireTableDataChanged()
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 );
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();
You could also use the following code if you have instanciated tableNameList as observable:
tableNameList.clear();
tableNameList.addAll(tableQuery.getResultList());
精彩评论