Lily S Lily S - 24 days ago 7
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].

Original

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);
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){
}
}

});

Answer

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,

Comments