DefaultTableModel doesn't refresh
-
05-06-2021 - |
Question
My JTable doesn't refresh after new data is entered into the database. I need to terminate and execute again to see results. I've included DefaultTableModel and fireTableDataChanged. What else did I miss? Thanks!
{
columnNames = new Vector();
data = new Vector();
try{
//database stuffs
}
catch{
}
DefaultTableModel tm = new DefaultTableModel();
JTable table = new JTable (tm);
JScrollPane scrollPane = new JScrollPane(table);
table = new JTable(data,columnNames)
{
public boolean isCellEditable(int row, int column){
return false;
}
public void newDataAvailable (TableModelEvent e){
}
};
scrollPane = new JScrollPane(table);
scrollPane.setBounds(33, 47, 256, 228);
panel.add(scrollPane);
}
Can I create a 'Refresh Button' and refresh the values instead?
No correct solution
OTHER TIPS
You shouldn't have to invoke fireTableDataChanged()
explicitly; DefaultTableModel
does this automatically when you update the model, as shown in this related example.
You create new JTable
instances. Create it just once and set the new model only to the existing JTable
(added to container properly).
- I have made a new project in that I have selected a new frame and drag a table, a label, a text field and a button from the swing controls to your frame.
2.create a table in back-end…
- Download rs2xml jar file from this link
- Add it to the project library…
Right click on the project > properties > library > add Jar/folder > select jar > ok
5.Then connect mysql using following code
public class DBConnect {
Connection connection = null;
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
System.out.println("connection successfully");
} catch (Exception ex) {
ex.printStackTrace();
}
return connection;
}
}
Call the function in the page using following code
con=new DBConnect(); statement=con.getConnection().createStatement();
7.Then create a update function type the following code…
void update_table() throws SQLException{
rs=statement.executeQuery("select * from details");
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
8.In the buttons action event type the following and call the update function
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Object name=jTextField1.getText();
String sql="insert into details (name) values('"+name+"')";
int resultset=statement.executeUpdate(sql);
update_table();
} catch (SQLException ex) {
Logger.getLogger(update.class.getName()).log(Level.SEVERE, null, ex);
}
}
9.Then run the project…
YOU can also Follow this Tutorial:--
How to refresh JTable after insert delete or update the data in java Netbeans ID