Java TableModel duplicating rows - How do I stop this from happening?

581 views Asked by At

So in application I've created a search for name page where the user will enter there the name and as the user types ( Every time a key is pressed) an SQL statement is ran that will get the records like 'name%'.

This works fine but when it comes to putting the values into the table everytime the user presses a key it append the found results to the table instead of replace the values. Meaning everytime a key is pressed...duplicate rows are generated.

So I was wondering if anyone had a solution to stop the rows being duplicated and instead replaced with the new values? Im using a default table model:

private DefaultTableModel tModel = new DefaultTableModel(0, 0);

My code:

 @Override
        public void keyReleased(KeyEvent e) {
            updateTable();
            table.setModel(tModel);
            formPanel.add(table);
                         tModel.fireTableDataChanged();

    }
    public void updateTable(){
         System.out.println("Save member 1");

            try{
             //CHANGE THE VALUES SO WHEN CLICKS SAVE MEM

                /*-------------------------------------*/   

            //Connection + Statement
            conDB = getConnection();
            stmt = conDB.createStatement();
            String searchSql = "select * from members where name "
                    + " LIKE '" + txtName.getText() +"%'"; 
                if(!txtName.getText().equals(""))
                {
                    r = stmt.executeQuery(searchSql);
                }
                System.out.println("searching");
                tModel.setColumnIdentifiers(columnNames);
                while(r.next()){
                    tModel.addRow(new Object[] { 
                        r.getString("name")
                    });
                } 
            }
            catch(SQLException er){
                System.out.println("Error was: " + er);
            }
    }

public searchBoth(){
        super("Search");
        this.setBounds(400, 500, 854,400);
        this.setVisible(true);
        mainCon.add(formPanel);

        formPanel.add(lblName);
        formPanel.add(txtName);
        txtName.addActionListener(this);
        addKeyListener(this);
        txtName.addKeyListener(this);
    }
1

There are 1 answers

4
Madhawa Priyashantha On BEST ANSWER

set rowCount to 0 and add rows .this will remove existing rows and add new rows

tModel.setRowCount(0);

code

System.out.println("searching");
tModel.setRowCount(0);// *********************remove current rows to replace
tModel.setColumnIdentifiers(columnNames);
while(r.next()){
    tModel.addRow(new Object[] { 
        r.getString("name")
    });
}