I have a JTextField
barcodeTextField
which accepts characters from the scanned barcode using a barcode scanner. From what I know, barcode scanning is like typing the characters very fast or copy-pasting the characters on the text field. barcodeTextField
is also used to show suggestions and fill up others fields with information (just like searching in Google where suggestions are shown as you type).
So far I implemented this using DocumentListener
:
barcodeTextField.getDocument().addDocumentListener(new DocumentListener() {
public void set() {
System.out.println("Pass");
// Do a lot of things here like DB CRUD operations.
}
@Override
public void removeUpdate(DocumentEvent arg0) {
set();
}
@Override
public void insertUpdate(DocumentEvent arg0) {
set();
}
@Override
public void changedUpdate(DocumentEvent arg0) {
set();
}
});
The problem is: If the barcode scanned has 13 characters, set()
is executed 13 times, and so with DB operations. Same goes when I type "123" to show suggestion list, set()
is executed 3 times.
I wanted set()
to get executed when the user stops typing on barcodeTextField
. In Javascript/JQuery
, this can be done using the keyup()
event and having setTimeout()
method inside, clearTimeout()
when user is still typing.
How to implement this behavior for JTextField
in Java?
The same way, Javascript has the timeout, Swing has a Timer. So if what you are looking for is achieved in Javscript using its "timer" fucntionality, you can see if you can get it working with a Swing Timers
For example
Timer
has arestart
. So you can set a delay on the timer for say 1000 milliseconds. Once text is being typed (first change in the document), checkif (timer.isRunning())
, andtimer.restart()
if it is, elsetimer.start()
(meaning first change in document). The action for the timer will only occur if one second passes after any document change. Any further changes occurring before the second is up, will cause the timer to reset. And settimer.setRepeats(false)
so the action only occurs onceYour document listener might look something like
Here's a complete example, where I "mock" typing, by explicitly inserting into the document (nine numbers) of the text field at a controlled interval of 500 milliseconds. You can see in the Timer owned by the DocumentListener that the delay is 1000 milliseconds. So as long as the typing occurs, the DocumentListener timer will not perform its action as the delay is longer than 500 milliseconds. For every change in the document, the timer restarts.