Skip to content

Instantly share code, notes, and snippets.

@AravindaM
Last active June 27, 2016 02:41
Show Gist options
  • Save AravindaM/54dadf20bcfe33ecfd33 to your computer and use it in GitHub Desktop.
Save AravindaM/54dadf20bcfe33ecfd33 to your computer and use it in GitHub Desktop.
Bar Code Reader
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Listener for reading data from the barcode Reader
* @author Aravinda
*
*/
public class BarcodeReader {
private static final long THRESHOLD = 100;
private static final int MIN_BARCODE_LENGTH = 8;
public interface BarcodeListener {
void onBarcodeRead(String barcode);
}
private final StringBuffer barcode = new StringBuffer();
private final List<BarcodeListener> listeners = new CopyOnWriteArrayList<BarcodeListener>();
private long lastEventTimeStamp = 0L;
public BarcodeReader() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() != KeyEvent.KEY_RELEASED) {
return false;
}
if (e.getWhen() - lastEventTimeStamp > THRESHOLD) {
barcode.delete(0, barcode.length());
}
lastEventTimeStamp = e.getWhen();
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (barcode.length() >= MIN_BARCODE_LENGTH) {
fireBarcode(barcode.toString());
}
barcode.delete(0, barcode.length());
} else {
barcode.append(e.getKeyChar());
}
return false;
}
});
}
protected void fireBarcode(String barcode) {
for (BarcodeListener listener : listeners) {
listener.onBarcodeRead(barcode);
}
}
public void addBarcodeListener(BarcodeListener listener) {
listeners.add(listener);
}
public void removeBarcodeListener(BarcodeListener listener) {
listeners.remove(listener);
}
}
@AravindaM
Copy link
Author

AravindaM commented Jul 6, 2015

Sample Uasage...

BarcodeReader barcodeReader = new BarcodeReader();
        barcodeReader.addBarcodeListener(new BarcodeListener() {
            @Override
            public void onBarcodeRead(String barcode) {
                                    System.out.println("Bar Code Value : ",barcode);
            }
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment