我正在将数据库中的数据填充到我的 JTable 中。添加新数据并按刷新按钮后,我想在检索新数据之前删除表上显示的现有行。如何删除现有行?
这是包含数据 [a,1] 的原始表。
这是我添加新数据 [b,1] 并按下刷新按钮后的表格。原始数据[a,1]仍然显示在表中:
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){
}
}
});