Lily S Lily S - 1 year ago 75
Java Question

How to remove rows in JTable before populating new data into the table?

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:

After insert

JButton refreshButton = new JButton("Refresh");
refreshButton.setBounds(188, 248, 101, 23);

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++)

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 (
Vector row = new Vector(columns);

for (int i=1; i <= columns; i++)
row.addElement( rs.getObject(i) );
System.out.println( rs.getObject(i).toString());



} // end while

} // end try

catch (Exception e){


Answer Source

I think that I saw this question,

1) search for ResultsetTableModel / TableFromDatabase (better)

  • (if Database Connection (so hard and lazy action) isn't closed during Applications lifecycle)

a) replace JTable contents

b) works with embeded Db of database placed in intranet immediatelly

  • dis

all processes is durring EDT, then GUI waiting for SQL statement

for most code examples required to move Xxx.close to the finally block

2) most complex workaround you have to use SwingWorker, better and easiest way is to load data from Runnable#Thread

3) you can remove row(s) from TableModel,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download