如何在每次单击搜索按钮时刷新JTable

时间:2016-03-18 12:26:19

标签: java sql-server swing

 try {
            DataBase DB = new DataBase();
            Connection con = DB.Connect();
            String sql;
            sql = "select Id,Name,FatherName, City, Address, Department,RStatus, DatePlacement\n"
                    + "from ECL where "
                    + "id like ? and  "
                    + "name like ? and FatherName like ? and "
                    + "City like ? and Address like ?";
            PreparedStatement pst = con.prepareStatement(sql);
            pst.setString(1, "%" + SearchId.getText() + "%");
            pst.setString(2, "%" + SearchName.getText() + "%");
            pst.setString(3, "%" + SearchFatherName.getText() + "%");
            pst.setString(4, "%" + SearchCity.getText() + "%");
            pst.setString(5, "%" + SearchAddress.getText() + "%");
            ResultSet rs = pst.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int MetaColum = rsmd.getColumnCount(); //adding colums in Jtable
            Vector col = new Vector();
            for (int i = 1; i <= MetaColum; i++) {
                col.addElement(rsmd.getColumnName(i));
            }
            ReTable.setColumnIdentifiers(col);
            while (rs.next()) {
                Vector rows = new Vector(); // to add rows in Jtable
                for (int j = 1; j <= MetaColum; j++) {
                rows.addElement(rs.getString(j));
                }
                ReTable.addRow(rows);
                ResultTable.setModel(ReTable);
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }      
         ReTable.fireTableDataChanged(); // Method to refresh the Jtable
    }  

如何使用新数据刷新jtable。它加载新数据,但每次我搜索新名称时它也包含旧数据,它给我正确的结果,但以前的搜索数据也保留在jtable中。我的问题是每次进行新的搜索时如何刷新jtable。提前致谢。

1 个答案:

答案 0 :(得分:0)

您没有删除模型中插入的先前行 ReTable 。在每个调用中,您将在此行中添加越来越多的行:

         ReTable.addRow(rows);

在启动查询之前从模型中删除所有行,或者为每个查询创建一个没有行的新模型。