Getting input from barcode scanner internally without textbox

Viewed 33623

I have a barcode scanner and in my java application I have to bring a popup to display all the information associated with the barcode from database when the product is scanned using barcode. I have no textbox on the application I have to handle this part internally. How do I do this ? any suggestion ? I am using swing for UI.

EDIT

Barcode scanner is USB one. If we scan something it will output the result into the textbox which has focus. But I have no textbox working on the page opened. Can i work with some hidden textbox and read the value there ?

3 Answers

Since was not able to get input via frame.addKeyListener I have used this utility class which uses KeyboardFocusManager :

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);
}

}
Related