I’m populating data from my database into my JTable. After I add new data and press Refresh button, I want to remove the existing row displayed on table before retrieving the new data. How can I remove the existing row?
Here is the original table with data [a,1].

This is the table after I add new data [b,1] and press refresh button. The original data [a,1] is still shown in the table:

JButton refreshButton = new JButton("Refresh");
refreshButton.setBounds(188, 248, 101, 23);
panel.add(refreshButton);
refreshButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
DefaultTableModel model = new DefaultTableModel(data,columnNames);
int rowCount = model.getRowCount();
for (int x = 0; x <=rowCount; x++)
{
model.removeRow(x);
}
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/watchlist","root","root");
String sql = "SELECT * FROM watchlist";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
while (rs.next())
{
Vector row = new Vector(columns);
for (int i=1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
System.out.println( rs.getObject(i).toString());
}
data.addElement(row);
table.revalidate();
table.repaint();
panel.repaint();
} // end while
} // end try
catch (Exception e){
}
}
});
I think that I saw this question,
1) search for
ResultsetTableModel / TableFromDatabase(better)a) replace
JTablecontentsb) works with embeded Db of database placed in intranet immediatelly
all processes is durring EDT, then GUI waiting for SQL statement
for most code examples required to move
Xxx.closeto the finally block2) most complex workaround you have to use
SwingWorker, better and easiest way is to load data fromRunnable#Thread3) you can remove row(s) from TableModel,