0

I have a program that checks prices by entering barcodes. I want the barcode field to automatically clear after reading the first barcode. It should hold entered information for only 5 seconds and clear up for the next entry.

Here is my code and am using JFrame. It's working well, but need some help on how to time the session of every entry.

private void txt_barcodeKeyReleased(java.awt.event.KeyEvent evt) {
    try {
        String sql = "select * from items where barcode=?" ;
        pst = conn.prepareStatement(sql);
        pst.setString(1, txt_barcode.getText());

        rs = pst.executeQuery();
        if (rs.next()) {
            String add1 = rs.getString("item_des");
            txt_description.setText(add1);
            String add2 = rs.getString("retail1");
            txt_price.setText(add2);
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex);
    }
}
Tom
  • 16,842
  • 17
  • 45
  • 54
Emma
  • 23
  • 1
  • 5

3 Answers3

1

Use the Timer with a 5 second delay and set the ActionPerformed to call .setText("") on the JTextField.

http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html

Wolsie
  • 144
  • 1
  • 13
  • i have tried to create a new timer but things are not working. can some one help n revise my code. i really want the barcode field to hold the user request for only 5 second and be ready for another request.please help n code for me. – Emma Feb 02 '15 at 08:30
0
  • Don't use KeyListener, espeically on text components. If you want know when a text component has changed, use a DocumentListener instead.
  • Use a Swing javax.swing.Timer to setup a callback at the required time in the future, just make sure you use setRepeats(false), so it will only trigger once.

See:

for more details

As an alternative, you could call selectAll on the textfield after you've populated. This will ensure that the next value applied (when typed) will wipe it clean.

setText will also clear the field and replace it's contents with what ever you specify

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You should use a thread or a timer, invoked after 5000 ms will clear the JTextField item. check this link Simple timer code

java.lang.Thread javadoc

Community
  • 1
  • 1
Wassim Jied
  • 25
  • 1
  • 5
  • Swing is not thread safe and any updates to the UI should be executed from within the context of the Event Dispatching Thread. You suggest violates the threading rules of Swing and doesn't suggest anything new that hasn't already been suggested – MadProgrammer Feb 01 '15 at 11:43
  • i have tried to create a new timer but things are not working. can some one help n revise my code. i really want the barcode field to hold the user request for only 5 second and be ready for another request.please help n code for me. – Emma Feb 02 '15 at 08:27