Hello, can anyone explain me why I'm still one step behind with this code?

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
    try {
        DefaultTableModel model=(DefaultTableModel)jTable1.getModel();
        model.setNumRows(0);
        String Name=jTextField1.getText();
        String sql= "SELECT * FROM APP.Workers WHERE First_Name LIKE'" +Name+ "%'";
        rs= stmt.executeQuery(sql);

        while (rs.next()) {
            String d1=(rs.getString("First_Name"));
            String d2=(rs.getString("Last_Name"));
            String d3=(rs.getString("Job_Title"));
            String d4=(Integer.toString(rs.getInt("ID")));
            
            model.addRow(new Object[]{d1,d2,d3,d4});
        }
    } catch (SQLException err) {
        JOptionPane.showMessageDialog(Workers.this, err.getMessage());
    }
}

I want to check what user write in TextField and then show matching records in Table. But, when I write to that TextField I'm one step behind- when I type first character nothing happens, when I type second it checks first character (and add matching records to the table) and so on...

Recommended Answers

All 4 Replies

You are responding to keyPressed, which happens when the user presses a key (duh!). But the input to the text field doesn't happen until the key is released and a valid character has been typed - so that's why you don't see the latest char in the getText. (Ps Even worse if it's (eg) an upper case character, because you'll get keyPressed events for the shift key AND the letter key before the text field is updated.)
Much better to implement your method in keyTyped, which is triggered when a character has been typed, and which automatically handles things like the shift key or alt-gr.

Well in fact, I've tried keyTyped and the result was the same. KeyPressed is there just because I experimented with different methods...

you have to add DocumentListener for listening any of changes in JTextComponents

this code for ??? AutoComplete ??? JTextField have got two big issues

1) most important rs (ResultSet) and stmt (Statement) must be closed into finally block, otherwise these Object stay in RAM until current application ended

2) your GUI waiting for returns from SQL server, during this long task isn't GUI accesible and freeze, load whole Resultset once time and implement AutoComplete JComboBox / JTextField

adding a DocumentListener worked great, thanks mKorbel :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.